swift中Map,FlatMap,Filter,Reduce的使用
1.map:
(1)可以用於遍歷陣列中每一個元素,將每個元素自身與自身相加,然後返回一個新的陣列:
let numberArr=[1,2,3,4,5,6]
//方式一:
let result1=numberArr.map { (number:Int) -> Int in
return
}
print("result1=\(result1)")
//方式二:
let result2=numberArr.map{ number in
return number+number
}
//方式三:
let result3=numberArr.map{$0+$0}
print("result3=\(result3)")
(2)可以用於過濾符合條件的陣列結果:
func mapTest2(){
let result=numberArr.map{ number ->Int? in
guard number%2 != 0 else{
return number
}
return nil
}
print(result)
}
2.FlatMap:
(1)不會返回陣列中不存在的nil,同時把Optional解包:
func flatMapTest1(){
let numberArr=[1,2,3,4,5,6]
let result=numberArr.flatMap{ number ->Int? in
guard number%2 != 0 else{
return number
}
return nil
}
print(result)
}
(2)合併兩個陣列:
func flatMapTest2(){
let nameArr=["張三","李四","王五"]
let ageArr=[20,40,23]
let result=ageArr.flatMap{ age in
nameArr.map{name in
(name,age)
}
}
print(result)
}
3.Filter 可以把陣列中的不符合條件的值過濾掉,返回一個新的陣列:
func filterTest(){
let numberArr=[1,2,3,4,5,6]
let result=numberArr.filter{$0%2 != 0}
print(result)
}
4.reduce:
(1)計算陣列元素的和
func filterTest(){
let numberArr=[1,2,3,4,5,6]
let result=numberArr.reduce(0){total,number in
return total + number
}
print(result)
}
(2)將一個數組合併成一個字串輸出:
func filterTest(){
let numberArr=[1,2,3,4,5,6]
//方式一:
let result1:String=numberArr.reduce(""){number1,number2 in
return "\(number1)" + "\(number2)"
}
print(result1)
//方式二:
let result2:String=numberArr.reduce(""){"\($0)"+"\($1)"}
print(result2)
}