数组变形 发表于 2017-09-29 | 分类于 Swift | 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162// 一、Map 转换let arr1 = [0,1,2,3,5]let result1 = arr1.map {$0 * $0}print(result1) // [0, 1, 4, 9, 25]// 二、FlatMaplet arr2 = [[1,2,3],[4,5,6]];let res = arr2.map { $0.map{ $0 + 2 } }print(res) // [[3, 4, 5], [6, 7, 8]]var flatRes = arr2.flatMap { $0.map{ $0 + 2 } }print(flatRes) // [3, 4, 5, 6, 7, 8]// 三、Fliter 过滤let arr3 = [0,1,2,3,4,5,6,7,8,9,10]let result3 = arr3.filter {$0 % 2 == 0}print(result3) //[0, 2, 4, 6, 8, 10]//map和fliter组合使用,寻找 100 以内同时满足是偶数并且是其他数字的 平方的数let result31 = (1..<10).map { $0 * $0 }.filter { $0 % 2 == 0 }print(result31) // [4, 16, 36, 64]// 四、Reduce 合并let arr4 = [0,1,2,3,5]let result4 = arr4.reduce(0,+)print(result4) //11// 五、Zip 是将两个序列的元素,一一对应合并成元组,生成一个新序列let a = [1, 2, 3, 4]let b = ["a", "b", "c", "d", "e"]let c = zip(a, b).map { $0 }print(c) // [(1, "a"), (2, "b"), (3, "c"), (4, "d")]/*zip 生成的序列通常会进行下一步处理。比如func loadColors(colors: [UIColor]) { zip(self.colorButtons, colors).forEach { (bt, color) in bt.color = color }}*/// zip和速记+来通过添加两个冲突的值来解析重复的键let keyNames2 = ["a", "b", "c", "a", "b"]let dict = Dictionary(zip(keyNames2, repeatElement(1, count: keyNames2.count)), uniquingKeysWith: +)print(dict) //["b": 2, "a": 2, "c": 1]// 六、 ForEach 跟for类型,forEach不返回任何值(有return的时候,使用for比forEach比较好)//theViews.forEach(view.addSubview)// 七、其它/* $0代表传入的元素本身,而不是下标 $0.0代表传入的元组的第一个值,如果元组被命名过了,则可以直接带名字 $0.age代表传入的模型的age属性 // 年龄升序排列 people.sort { $0.age < $1.age } // 检查是否有小于18岁的 people.contains { $0.age < 18 } // 忽略大小写的排序 people.sort { $0.name.uppercased() < $1.name.uppercased() } */ 打赏支持一下呗! Donate WeChat Pay Alipay