# [函数式Swift]从 map 函数看泛型

``````extension Array {
func map<T>(transform: (Element) -> T) -> [T] {
var result: [T] = []
for x in self {
result.append(transform(x))
}
return result
}
}
``````

OC中用过RAC的应该熟悉 map 这个函数。接下来要做的通过一些小案例来解析这段代码

``````func incrementArray(xs: [Int]) -> [Int] {
var result: [Int] = []
for x in xs {
result.append(x + 1)
}
return result
}
``````

``````func doubleArray1(xs: [Int]) -> [Int] {
var result: [Int] = []
for x in xs {
result.append(x * 2)
}
return result
}
``````

``````func computeIntArray(xs: [Int], transform: (Int) -> Int) -> [Int] {
var result: [Int] = []
for x in xs {
result.append(transform(x))
}
return result
}
//注意这里 transform: Int -> Int 是一个函数 , 接受整型 然后返回整型
``````

``````
computeIntArray(xs) { x in x * 2 }
computeIntArray(xs) { x in x + 1 }

``````

``````func isEvenArray(xs: [Int]) -> [Bool] {
computeIntArray(xs) { x in x % 2 == 0 }
}
``````

``````
func computeBoolArray(xs: [Int], transform: (Int) -> Bool) -> [Bool] {
var result: [Bool] = []
for x in xs {
result.append(transform(x))
}
return result
}

``````

computeBoolArray 和 computeIntArray 的定义是相同的；唯一的区别在于类型签名 (type signature)。假如定义一个相似的函数 computeStringArray 来支持 String 类型，其函数体将会与先前两个函数完全一致。事实上，相同部分的代码可以用于任何类型。真正想做的是写一个能够适用于每种可能类型的泛型函数：

``````func genericComputeArray1<T>(xs: [Int], transform:(Int) -> T) -> [T] {
var result: [T] = []
for x in xs {
result.append(transform(x))
}
return result
}
``````

``````func map<Element, T>(xs: [Element], transform: (Element) -> T) -> [T] {
var result: [T] = []
for x in xs {
result.append(transform(x))
}
return result
}
``````

``````extension Array {
func map<T>(transform: (Element) -> T) -> [T] {
var result: [T] = []
for x in self {
result.append(transform(x))
}
return result
}
}
``````

transform 参数中所使用的 Element 类型源自于 Swift 的 Array 中对 Element 所进行的泛型定义。