美文网首页
Swift-05.Array的常见操作

Swift-05.Array的常见操作

作者: Fight_ing | 来源:发表于2020-12-01 17:55 被阅读0次
    • map / filter / reduce
    var arr = [1, 2, 3, 4]
    // [2, 4, 6, 8]
    var arr2 = arr.map { $0 * 2 }
    // [2, 4]
    var arr3 = arr.filter { $0 % 2 == 0 } // 10
    var arr4 = arr.reduce(0) { $0 + $1 } // 10
    // 可简写为
    var arr5 = arr.reduce(0, +)
    
    • map接收函数作为参数
    func double(_ i: Int) -> Int { i * 2 } 
    var arr = [1, 2, 3, 4]
    // [2, 4, 6, 8] 
    print(arr.map(double))
    
    • compactMap默认解包并去除nil
    var arr = ["123", "test", "jack", "-30"] 
    
    // [Optional(123), nil, nil, Optional(-30)] 
    var arr2 = arr.map { Int($0) }
    
    // [123, -30]
    var arr3 = arr.compactMap { Int($0) }
    
    • 使用reduce实现mapfilter函数的功能
    var arr = [1, 2, 3, 4]
    
    // [2, 4, 6, 8]
    print(arr.map { $0 * 2 }) 
    // 等价于👆函数功能
    print(arr.reduce([]) { $0 + [$1 * 2] })
    
    // [2, 4]
    print(arr.filter { $0 % 2 == 0 }) 
    // 等价于👆函数功能
    print(arr.reduce([]) { $1 % 2 == 0 ? $0 + [$1] : $0 })
    
    • map,flatMap功能对比
    var arr = [1, 2, 3]
    // [[1], [2, 2], [3, 3, 3]] 拿到什么(数组),返回数组(二维数组)就放什么,不做处理。
    var arr2 = arr.map { Array.init(repeating: $0, count: $0) }
    // [1, 2, 2, 3, 3, 3] 将拿到的数组中的元素取出放到返回数组(一维数组)中。扁平化处理。
    var arr3 = arr.flatMap { Array.init(repeating: $0, count: $0) }
    
    • lazy的优化map
    let arr = [1, 2, 3]
    let result = arr.lazy.map {
        (i: Int) -> Int in 
        print("mapping \(i)") 
        return i * 2
    }
    print("begin-----")
    print("mapped", result[0]) 
    print("mapped", result[1]) 
    print("mapped", result[2]) 
    print("end----")
    // 第一次用到时,才会执行相应逻辑
    begin----- 
    mapping 1 
    mapped 2 
    mapping 2 
    mapped 4 
    mapping 3 
    mapped 6 
    end----
    
    • mapflatMap可选值Optional处理中的应用
    var num1: Int? = 10
    // Optional(20)
    var num2 = num1.map { $0 * 2 }
    
    var num3: Int? = nil
    // nil,发现$0为nil直接返回nil
    var num4 = num3.map { $0 * 2 }
    

    mapflatMap对比

    var num1: Int? = 10
    // Optional(Optional(20)), map还是会对可选值再包装一层
    var num2 = num1.map { Optional.some($0 * 2) }
    
    // Optional(20), flatMap发现已经是可选值,就不会再包装了
    var num3 = num1.flatMap { Optional.some($0 * 2) }
    

    可用于简化代码

    // 示例一:
    var num1: Int? = 10
    var num2 = (num1 != nil) ? (num1! + 10) : nil 
    var num3 = num1.map { $0 + 10 }
    // num2、num3是等价的
    
    // 示例二:
    var fmt = DateFormatter()
    fmt.dateFormat = "yyyy-MM-dd"
    var str: String? = "2011-09-10"
    // old
    var date1 = str != nil ? fmt.date(from: str!) : nil 
    // new
    var date2 = str.flatMap(fmt.date)
    
    // 示例三:
    var score: Int? = 98
    // old
    var str1 = score != nil ? "socre is \(score!)" : "No score" 
    // new
    var str2 = score.map { "score is \($0)" } ?? "No score"
    
    // 示例四:
    struct Person {
        var name: String
        var age: Int
    }
    var items = [
        Person(name: "jack", age: 20), 
        Person(name: "rose", age: 21), 
        Person(name: "kate", age: 22)
    ]
    // old
    func getPerson1(_ name: String) -> Person? {
        let index = items.firstIndex { $0.name == name } 
        return index != nil ? items[index!] : nil
    }
    // new
    func getPerson2(_ name: String) -> Person? {
        return items.firstIndex { $0.name == name }.map { items[$0] }
    }
    
    // 示例五:
    struct Person {
        var name: String
        var age: Int
        init?(_ json: [String : Any]) {
            guard let name = json["name"] as? String, 
            let age = json["age"] as? Int else {
                return nil
            }
            self.name = name 
            self.age = age
        } 
    }
    var json: Dictionary? = ["name" : "Jack", "age" : 10] 
    // old
    var p1 = json != nil ? Person(json!) : nil
    // new
    var p2 = json.flatMap(Person.init)
    

    相关文章

      网友评论

          本文标题:Swift-05.Array的常见操作

          本文链接:https://www.haomeiwen.com/subject/qsiswktx.html