# Why Coding like This?—— Reduce 函数揭秘

### 3.Reduce 函数揭秘

#### Example:

``````//例一：
let intArray = [1,2,3,4]

var sum = intArray.reduce(0){
result, x in
result + x
}
``````

#### 1.开篇

``````//例二：
func sum(xs:[Int])->Int{
var result:Int = 0
for x in xs{
result += x
}
return result
}
//不妨测试下
sum(intArray)//print 10
``````

#### 2.过渡

``````//例三：
func multiplicator(xs:[Int])->Int{
var result:Int = 1
for x in xs{
result = x * result
}
return result
}
multiplicator(intArray)//输出24
``````

``````//例四：
func jointStringArray(xs:[String])->String{
var result :String = ""

for x in xs{
result += x
}
return result
}
let helloworld = ["hello"," ","world","!","say"," ","by"," ","optionalswift"]
jointStringArray(helloworld)//输出"hello world!say by optionalswift"
``````

``````//例五：hyphen 意思为连字符`-`
func jointStringArrayByHyphen(xs:[String])->String{
var result : String = "整合后的字符串为："
for x in xs{
result = result + "-" + x  //注意右侧是一个类似combine(result,x)函数进行处理 得到整合后的结果给result
}
return result
}
let newArray = ["hello","world","say","By","optional"]
jointStringArrayByHyphen(newArray)//输出"整合后的字符串为：-hello-world-say-By-optional"
``````

#### 3.高潮

``````//例六：
func myReduce<T,U>(arr:[T],initialValue:U,combine:(U,T)->U)->U{
var result = initialValue //赋值初始值 类型为U 并且是作为结果值返回的
for elem in arr{
result = combine(result,elem)   //注意右侧是传入的闭包 该闭包类型为(U,T)->U,即把上一次的结果值依次和数组元素做拼接处理，该处理可在闭包中实现，取决于你
}
return result
}
myReduce(newArray, "整合后的字符串为："){
result , elem in //注意result ,x 于combine(result,elem)相对应
return result + "-" + x //注意这里return 其实是可以省略的！
}
``````

#### 4.落幕

``````func sumUsingReduce(xs:[Int])->Int{
return myReduce(xs,0){result, x in result + x}
}
``````

``````func sumUsingReduce(xs:[Int])->Int{
return myReduce(xs,0,+)
}
``````

``````func mapUsingReduce<T,U>(xs:[T],f:T->U)->[U]{
return xs.reduce([]){result,x in result + [f(x)]}//使用了系统API 尝试用自定义的
}
``````

``````filterUsingReduce<T>(xs:[T],check:T->Bool)->[T]{
return xs.reduce([]){
return check(x) ? result + [x] : result //使用了系统API 尝试用自定义的
}
}
``````

map，filter，reduce 小节至此结束！ 希望对大家有收获！