map
map
方法的定义
public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
map函数接收一个闭包做参数,闭包本身参数是原数组的元素,闭包返回值是一个泛型,由泛型对象组成的数组作为map函数的返回值。
- 示例
-
返回与原数组相同的类型
let numbers = [0, 1, 2, 3, 4, 5] let addNumbers = numbers.map { number in return number + 1 } // [1, 2, 3, 4, 5, 6] print(addNumbers)
-
返回与原数组不同的类型
class Person: NSObject { var name = "" var age = 0 var height: Float = 0 } let personDictArray = [["name": "zhangsan", "age": 21, "height": 185], ["name": "lisi", "age": 22, "height": 180], ["name": "lihua", "age": 11, "height": 120]] let personArray = personDictArray.map { (dict) -> Person in let person = Person() if let name = dict["name"] as? String { person.name = name } if let age = (dict["age"] as AnyObject).int32Value { person.age = Int(age) } if let height = (dict["height"] as AnyObject).floatValue { person.height = height } return person }
- 注意
无论原数组是否存在可选类型的元素,map操作返回的结果数组元素都可以是可选类型的
let numbers: Array = [0, 1, 2, 3, 4, 5]
let optionalNumbers = numbers.map { number -> String? in
let killNumber = 1
if number == killNumber {
return nil
} else {
return "我是\(number),不是\(killNumber)"
}
}
// Optional("我是0,不是1"), nil, Optional("我是2,不是1"), Optional("我是3,不是1"), Optional("我是4,不是1"), Optional("我是5,不是1")
print(optionalNumbers)
flatMap
flatMap
方法的定义
- 重载1
public func flatMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
flatMap
函数重载1接收一个闭包做参数,闭包本身参数是原数组的元素,闭包返回值是一个泛型,由非可选类型的泛型对象组成的数组作为flatMap函数的返回值。与map函数基本相同,不同之处在于返回的数组不存在可选类型的元素。
-
重载2
public func flatMap<SegmentOfResult : Sequence>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element]
flatMap
函数重载2接收一个闭包做参数,闭包本身参数是原数组的元素,闭包返回值是一个泛型,与重载1不同的是,flatMap
返回泛型对象的元素组成的数组做为返回值。
2.示例
-
重载1示例
let possibleNumbers = ["1", "2", "three", "///4///", "5"] let mapped: [Int?] = numbers.map { str in Int(str) } // [1, 2, nil, nil, 5] let flatMapped: [Int] = numbers.flatMap { str in Int(str) } // [1, 2, 5]
-
重载2示例
let originalNumbers = [1, 2, 3, 4] let mapped1 = originalNumbers.map { Array(repeating: $0, count: $0) } // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]] let flatMapped1 = originalNumbers.flatMap { Array(repeating: $0, count: $0) } // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
filter
1.filter
方法的定义
public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]
filter
方法接收一个闭包做参数,闭包本身参数是原数组的元素,闭包返回布尔值,filter
方法的返回值由原数组元素同样类型的元素组成,也就是闭包返回值为true
的元素。
2.示例
-
从一个字符串数组中找出所有长度小于5的元素
let cast = ["Vivien", "Marlon", "Kim", "Karl"] let shortNames = cast.filter { $0.characters.count < 5 } print(shortNames) // Prints "["Kim", "Karl"]"
Reduce
1.Reduce
方法的定义
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
Reduce
方法接收一个闭包做参数,闭包本身包含两个参数,参数1是上一次执行闭包操作的结果值,参数2是原数组的元素,闭包一个泛型对象,Reduce
方法的返回值就是最终的这个泛型对象。
2.示例
-
计算一个整型数组的所有元素的和
let numbers1 = [1, 2, 3, 4] let addTwo: (Int, Int) -> Int = { x, y in x + y } let numberSum = numbers1.reduce(0, addTwo) // 'numberSum' == 10
小练习
给定一些人,计算给所给出的这些人中年龄在15-22岁之间的平均身高。
let personDictArray = [["name": "zhangsan", "age": 25, "height": 185],
["name": "lisi", "age": 22, "height": 180],
["name": "lihua", "age": 21, "height": 170],
["name": "lihua", "age": 18, "height": 173],
["name": "lihua", "age": 19, "height": 177],
["name": "lihua", "age": 11, "height": 120]]
let filterPerson = personDictArray.map { (dict) -> Person in
let person = Person()
if let name = dict["name"] as? String {
person.name = name
}
if let age = (dict["age"] as AnyObject).int32Value {
person.age = Int(age)
}
if let height = (dict["height"] as AnyObject).floatValue {
person.height = height
}
return person
}.filter { person -> Bool in
return person.age >= 15 && person.age <= 22
}
let averageHeight = filterPerson.reduce(0) { (result, person) -> Float in
return result + person.height
} / Float(filterPerson.count)
print(averageHeight)