# Why Coding like this ? ——Map函数揭秘

### 1.Map函数揭秘

#### Example:

``````//例一
let intArray = [1,2,3]
var result = intArray.map{ \$0 * 2}  //输出[2,4,6]
``````

#### why coding like this?

``````//例二：
func doubleArrayByTwo(xs:[Int])->[Int]{
var result :[Int] = []

for x in xs{
result.append(x * 2)
}
return result
}
``````

``````result = doubleArrayByTwo(intArray) //返回[2,4,6]
``````

``````//例三：线性变换 y = 2x + 3
func linealMeasureArray(xs:[Int])->[Int]{
var result :[Int] = []

for x in xs{
result.append(x * 2 + 3)  //仅仅只是括号中的代码改变了下而已
}
return result
}
``````

``````//例四：
func handleIntArray(xs:[Int],f:Int->Int)->[Int]{
var result :[Int] = []

for x in xs {
result.append(f(x))
}

return result
}
``````

``````//输出 3 5 7
result = handleIntArray(intArray){
x in
return 2 * x + 1      //2 * x + 1 就是闭包的处理体
}
``````

``````func handleClosure(x:Int)->Int{
return 2 * x + 1
}
result = handleIntArray(intArray, handleClosure)
``````

``````//例五：
func handleBoolArray(xs:[Int],f:Int->Bool)->[Bool]{
var result :[Bool] = []

for x in xs {
result.append(f(x))
}

return result
}
``````

``````//例六：
func genericComputeArray<U>(xs:[Int],f:Int->U)->[U]{
var result :[U] = []

for x in xs {
result.append(f(x))
}

return result
}
``````

``````//例七：
func myMap<T,U>(xs:[T],f:T->U)->[U]{
var result:[U] = []
for x in xs{
result.append(f(x))
}
return result
}
myMap(intArray){
x in x * 2
}//输出 [2,4,6]
``````