美文网首页
swift 高阶函数 map filter reduce

swift 高阶函数 map filter reduce

作者: _秃头少女_ | 来源:发表于2019-07-10 18:32 被阅读0次
            //针对 数组 字典 集合
            //map简写法
            let values = [2.0,3.0,5.0,7.0]
            let squares = values.map{$0 * $0}
            print(squares)//[4.0, 9.0, 25.0, 49.0]
            //map正常写法
            let squares2 = values.map({
                (value: Double) -> Double in
                return value * value
            })
            print(squares2)//[4.0, 9.0, 25.0, 49.0]
            //filter
            let digits = [1, 4, 10, 15]
            let even = digits.filter { $0 % 2 == 0 }
            print(even)//[4, 10]
            
            let even1 = digits.filter{
                (number) -> Bool in
                return number % 2 == 0
            }
            print(even1)//[4, 10]
            //reduce
            let reduceSouce = [2,3,5,7]
            let total = reduceSouce.reduce(10, +)
            print(total)//27
            
            let codes = ["abc", "def", "ghi"]
            let total1 =  codes.reduce("", +)
            print(total1)//abcdefghi
            
            //value1 代表初始值 "===="以及后面拼接后的值
            //value2 代表string 数组里面的元素
            let string = ["wo","de","who"]
            let total2 = string.reduce("===="){
                value1,value2 in "\(value1),\(value2)"
            }
            print(total2)//====,wo,de,who
    
            //flatMap  合并数组 集合
            let collection = [[2,4,5],["a","b"],[9,5]]
            let resultCollection = collection.flatMap{$0}
            print(resultCollection)//[2, 4, 5, "a", "b", 9, 5]
            
            //flatMap还“知道”可选值的概念,它将会把集合中的nil元素移除掉
            let people: [String?] = ["Tom", nil, "Peter", nil, "Harry"]
            let valid = people.flatMap { $0 }
            // ["Tom", "Peter", "Harry"]
            
       //https://www.jianshu.com/p/1b4a8b4517bd     
    

    相关文章

      网友评论

          本文标题:swift 高阶函数 map filter reduce

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