map:
可以对集合类型中的每一个元素做一次处理,转换成一个新数组。
数组
let colors = ["red", "blue", "yellow", "white"]
let counts = colors.map { (string: String) -> Int in
return string.characters.count
}
// 简化
let counts = colors.map { $0.characters.count }
// 结果 [3, 4, 6, 5]
class Color {
var name: String
init(name: String) {
self.name = name
}
}
// 转换为对象数组
let colorObjs = colors.map {
return Color(name: $0)
}
for obj in colorOjbs {
print(obj.name)
}
// red
// blue
// yellow
// white
集合
let ColorsSet: Set = ["red", "blue", "yellow", "white"]
let colorsCount = ColorsSet.map { $0.count }
// 结果: [3, 4, 6, 5]
字典
let dict = [1: "one", 2: "two", 3: "three"]
let keys = dict.map { $0.key } // [2, 3, 1]
let values = dict.map { $0.value } // ["two", "three", "one"]
flatMap:
不包含nil
flatMap
返回后的数组中不存在nil
,同时它会把Optional
解包。
let colors = ["red", "blue", "yellow", ""]
let countsOfMap = colors.map { item -> Int? in
let length = item.characters.count
guard length > 0 else {
return nil
}
return length
}
// 结果: [3, 4, 6, nil]
let counts = colors.flatMap { item -> Int? in
let length = item.characters.count
guard length > 0 else {
return nil
}
return length
}
// 结果 [3, 4, 6]
打开数组
flatMap
还能把数组中存有数组的数组(二维数组、N维数组)一同打开变成一个新的数组。
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let arr1 = array.map{ $0 }
// arr1: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let arr2 = array.flatMap{ $0 }
// arr2: [1, 2, 3, 4, 5, 6, 7, 8, 9]
合并数组
flatMap
也能把两个不同的数组合并成一个数组,这个合并的数组元素个数是前面两个数组元素个数的乘积。
let fruits = ["Apple", "Orange", "Puple"]
let counts = [2, 3, 5]
let newArray = counts.flatMap { count in
fruits.map ({ fruit in
return fruit + " \(count)"
})
}
// ["Apple 2", "Orange 2", "Puple 2", "Apple 3", "Orange 3", "Puple 3", "Apple 5", "Orange 5", "Puple 5"]
filter:
过滤,可以对数组中的元素按照某种规则进行一次过滤。
let numbers = [1, 3, 5, 7, 9]
let filterNumbers = numbers.filter { $0 <= 5 }
// [1, 3, 5]
reduce:
计算,可以对数组的元素进行计算。
// 返回result,现在result是字符串
let fruits = ["Apple", "Orange", "Puple"]
let string = fruits.reduce("", {
// $0: result, $1: 数组的值
return $0 == "" ? $1 : $0 + "," + $1
})
// Apple,Orange,Puple