一、声明
- 内容仅作为博主个人学习的一个总结输出,仅供参考,若对你产生了一丝帮助,荣幸之至。
二、map
在集合类型Array,Dictionary,Set中使用
作用:循环集合将同样的操作应用于集合的每一个元素。
//: map将整型数组中的每个数字都加10
let data = [1, 2, 3, 4, 5]
let res = data.map { $0 + 10 }
//: 函数表达式可以更清晰的写成:
let res2 = data.map { (val: Int) -> Int in
return val + 10
}
//: 闭包有一个单独参数,但是swift能推断类型,我们可以不用设置参数类型和return.
let res3 = data.map { val in val + 10 }
//: 将数字翻译成英文
let words = data.map { NumberFormatter.localizedString(from: $0 as NSNumber, number: .spellOut) }
print("\(words)") //: ["one", "two", "three", "four", "five"]
//: 字典中的使用
let dict = ["Fly": 80.0, "Elephant": 90, "FlyElephant": 100]
let dictResult = dict.map{ name,score in score * 0.5 }
print("\(dictResult)") //: [50.0, 40.0, 45.0]
三、Filter
在集合类型Array,Dictionary,Set中使用
作用:循环一个集合并返回符合包含条件的数组元素
let digits = [1,2,3,4]
//: 筛选能被2整除的数
let even = digits.filter { $0 % 2 == 0 }
print("\(even)") //: [2, 4]
四、Reduce
在集合类型Array,Dictionary,Set中使用
作用:会拼接集合中所有的值来创建一个新的值。
//: 相加
let items = [2.0, 4.0, 6.0, 8.0]
let total = items.reduce(1.0, +)
print("\(total)") //: 21.0
//: 字符串拼接
let names = ["Fly", "Elephant", "FlyElephant"]
let text = names.reduce("", +)
print("\(text)") //: FlyElephantFlyElephant
//: 拼接参数是一个闭包同样可以使用尾闭包的写法
let tails = names.reduce("~~~") {text, name in "\(text),\(name)"}
print("\(tails)")
~~~,Fly,Elephant,FlyElephant
五、字符串和数组互转
//: 字符串转数组
let str = "I am Gomu"
let array = str.components(separatedBy:" ")
print("字符串转数组:\(array)") //[I, am, Gomu]
//: 非字符串数组转字符串
let data = [1,2,3,4,5]
//: 非字符串数组转字符串
//: 写法一
let dataStr = data.map(String.init)
//: 写法二
let dataStr = data.map{String($0)}
//: 写法三
let dataStr = data.map{"\($0)"}
let result = dataStr.joined(separator: ",")
print("数组转字符串:\(result)") //: 1,2,3,4,5
//: 字符串数组转字符串
let arr = ["Bob","Swfit","Anna","Chris"]
let strr = arr.joined(separator: ",") //: Bob, Swfit, Anna, Chris
六、总结
下次遇到需要遍历集合类型的时候可以通过以下几点进行map,filter和reduce判断。
- map返回一个包含每个元素都进行转变的数组
- fiter返回一个仅仅符合条件的数据的数组
- reduce返回单个值,值是通过每个元素的联合闭包和一个初始值计算而成
网友评论