參考
Swift高階函數(shù):Map,F(xiàn)ilter励背,Reduce
map
不使用map函數(shù)來操作數(shù)組(同時(shí)熟悉閉包的產(chǎn)生過程):
//第一種:不使用map來操作數(shù)組
let mapArray = [1,7,4,8,2]
func add1(a: Int) -> String {
return "\(a)個(gè)"
}
func newArr(a: [Int]) -> [String] {
var new = [String]()
for b in a {
new.append("\(b)個(gè)")
}
return new
}
let mapArray2 = newArr(a: mapArray)
func newArr2(a: [Int],f: ((Int) -> String)) -> [String] {
var new = [String]()
for b in a {
new.append(f(b))
}
return new
}
let mapArray3 = newArr2(a: mapArray, f: add1(a:))
let mapArray4 = newArr2(a: mapArray, f: {(b: Int) -> String in return "\(b)個(gè)"})
print(mapArray4)
let mapArray5 = newArr2(a: mapArray, f: {b in return "\(b)個(gè)"})
print(mapArray5)
let mapArray6 = newArr2(a: mapArray, f: {b in "\(b)個(gè)"})
print(mapArray6)
let mapArray7 = newArr2(a: mapArray, f: {"\($0)個(gè)"})
print(mapArray7)
使用map函數(shù):
map函數(shù)相當(dāng)于系統(tǒng)提供的"newArr2"函數(shù),我們只需要寫閉包部分
//第二種:使用map來操作數(shù)組
let mapArray8 = mapArray.map({"\($0)個(gè)"})
print(mapArray8)
let map2Array = ["1","5","3","9","8"]
let map2Array2 = map2Array.map({$0 + "個(gè)"})
print(map2Array2)
filter
不使用filter函數(shù)來操作數(shù)組(同時(shí)熟悉閉包的產(chǎn)生過程):
//第一種:不使用filter函數(shù)來篩選數(shù)組
//篩選出大于30的數(shù)
let money = [12,54,34,76,11]
//--------
//直接粗暴型
func filterArr(a: [Int]) -> [Int] {
var newArr = [Int]()
for b in a {
if b > 30 {
newArr.append(b)
}
}
return newArr
}
let money2 = filterArr(a: money)
//-------
//包含函數(shù)參數(shù)型
func compare(a: Int) -> Bool {
if a > 30 {
return true
}
else {
return false
}
}
func filterArr2(a: [Int], f: ((Int) -> Bool)) -> [Int] {
var newArr = [Int]()
for b in a {
if f(b) {
newArr.append(b)
}
}
return newArr
}
let money3 = filterArr2(a: money, f: compare(a:))
//--------
//閉包型
let money4 = filterArr2(a: money, f: { (b) -> Bool in return b>30 })
print(money4)
let money5 = filterArr2(a: money, f: { b in return b>30 })
print(money5)
let money6 = filterArr2(a: money, f: { b in b>30 })
print(money6)
let money7 = filterArr2(a: money, f: { $0 > 30 })
print(money7)
使用filter函數(shù):
filter函數(shù)相當(dāng)于系統(tǒng)提供的"filterArr2"函數(shù),我們只需要寫閉包部分
//第二種:使用filter函數(shù)來篩選數(shù)組
let money8 = money.filter({$0 > 30})
print(money8)
let moneyP = [3,2,11,65,7]
let moneyP2 = moneyP.filter({ $0 < 10 })
print(moneyP2)
reduce
對(duì)數(shù)組進(jìn)行計(jì)算操作
let subArr = [1,2,3,4,5,6]
let sum = subArr.reduce(0, {$0 + $1})
print(sum)
let mul = subArr.reduce(1, {$0 * $1})
print(mul)