# swift，Array的高阶函数使用一： map

image.png

1. 方法的作用
map: 可以对数组中的每一个元素做一次处理, 返回一个泛型的数组。

2. 方法的官方声明和注释(不想看的可略过)
Returns an array containing the results of mapping the given closure over the sequence's elements. In this example, 'map' is used first to convert the names in the array to lowercase strings and then to count their characters.
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { 0.count }
/// // 'letterCounts' == [6, 6, 3, 4]
Parameter transform: A mapping closure. 'transform' accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this sequence.

public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]

##### 四、 使用和详解
• 案例一
let arrayAny: [Any?] = [1, 2, 3, 4, 5, nil, "a", 8, "9"]
print(arrayAny)
let arrInt = arrayAny.map { (obj) -> Int in
if obj is Int {
return obj as! Int
} else {
return 0
}
}
print("arrInt: \(arrInt)")
// arrInt: [1, 2, 3, 4, 5, 0, 0, 8, 0]

public func map(_ transform: (Any?) throws -> Int) rethrows -> [Int]

### 返回的值为什么不是可选的呢？

let arrInt2 = arrayAny.map {
return (\$0 is Int) ? \$0 : 0
}
print("arrInt2: \(arrInt2)")
// arrInt2: [Optional(1), Optional(2), Optional(3), Optional(4), Optional(5), Optional(0), Optional(0), Optional(8), Optional(0)]

### \$0是怎么回事？

*/

• 案例二

let arrayString = ["Ann", "Bob", "Tom", "Lily", "HanMeiMei", "Jerry"]

print("-----------------案例二----------------------")
let arrayString = ["Ann", "Bob", "Tom", "Lily", "HanMeiMei", "Jerry"]
// 计算每个元素的个数，生成个数数组
let arrayCount = arrayString.map { (str) -> Int in
return str.count
}
print("arrayCount: \(arrayCount)")
// arrayCount: [3, 3, 3, 4, 9, 5]

/*

public func map(_ transform: (String) throws -> Int) rethrows -> [Int]
*/

let arrayCount2 = arrayString.map { return \$0.count }
print("arrayCount2: \(arrayCount2)")
//arrayCount2: [3, 3, 3, 4, 9, 5]

let arrayCount3 = arrayString.map { \$0.count }
print("arrayCount3: \(arrayCount3)")
//arrayCount3: [3, 3, 3, 4, 9, 5]

### 泛型T是如何确定类型的？

let arrayDict = arrayString.map { [\$0: \$0.count] }
print("arrayDict: \(arrayDict)")
// arrayDict: [["Ann": 3], ["Bob": 3], ["Tom": 3], ["Lily": 4], ["HanMeiMei": 9], ["Jerry": 5]]

let arrayLow = arrayString.map { \$0.lowercased() }
print("arrayLow: \(arrayLow)")
// arrayLow: ["ann", "bob", "tom", "lily", "hanmeimei", "jerry"]

let arrayI = arrayString.map { \$0.contains("i") ? \$0 : "" }
print("arrayI: \(arrayI)")
// arrayI: ["", "", "", "Lily", "HanMeiMei", ""]

swift学习