閉包是 Swift 中一個重要的知識點,不僅在開發(fā)中能夠幫助解決很多問題(如逆向傳值),而且在許多官方系統(tǒng)庫方法中都能看到它的身影,尤其是在集合中提供了很多高階函數(shù)來對元素進行訪問及操作,這些函數(shù)大量使用了閉包。重點需要掌握下面列舉的函數(shù)。
sort — 排序
// 準(zhǔn)備一個數(shù)組
var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
// 這種默認是升序
array.sorted()
// 如果要降序
array.sort { (str1, str2) -> Bool in
return str1 > str2
}
forEach — 遍歷
// 準(zhǔn)備一個數(shù)組
var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
// 遍歷
array.forEach( { str in
print(str)
});
filter — 篩選
// 準(zhǔn)備一個數(shù)組
var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
// 刷選
array.filter { (str) -> Bool in
// 篩選里面的閉包必須是返回Bool類型的閉包
str.hasPrefix("A")
}.forEach({
a in print(a)
})
map — 轉(zhuǎn)換
// 準(zhǔn)備一個數(shù)組
var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
// 閉包返回一個變換后的元素,接著將所有這些變換后的元素組成一個新的數(shù)組
array.map( { (str) -> String in
"Hello " + str
}).forEach({
str in print(str)
})
reduce — 合歸
// map和filter方法都是通過一個已存在的數(shù)組,生成一個新的、經(jīng)過修改的數(shù)組。然而有時候我們需要把所有元素的值合并成一個新的值
var sum: [Int] = [11, 22, 33, 44]
// reduce 函數(shù)第一個參數(shù)是返回值的初始化值 result是中間結(jié)果 num是遍歷集合每次傳進來的值
var total = sum.reduce(0) { (result, num) -> Int in
return result + num
}
print(total)
first(where:) — 篩選第一個符合條件(Swift 4.1)
var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
let element = array.first(where: { $0.hasPrefix("A") })
print(element!)
//Animal
last(where:) — 篩選最后一個符合條件(Swift 4.2)
var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
let element = array.last(where: { $0.hasPrefix("A") })
print(element!)
//Aunt
removeAll(where:) — 刪除(Swift 4.2)
高效根據(jù)條件刪除,比filter內(nèi)存效率高,指定不想要的東西,而不是想要的東西
var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
array.removeAll(where: { $0.hasPrefix("A") })
print(array)
//["Baby", "Google"]
allSatisfy — 條件符合(Swift 4.2)
// 判斷數(shù)組的所有元素是否全部大于85
let scores = [86, 88, 95, 92]
// 檢查序列中的所有元素是否滿足條件,返回 Bool
let passed = scores.allSatisfy({ $0 > 85 })
print(passed)
compactMap — 轉(zhuǎn)換(Swift 4)
let arr: [Int] = [1, 2, 34, 5, 6, 7, 8, 12, 45, 6, 9]
// 返回操作的新數(shù)組(并不是篩選),數(shù)組、字典都可以使用
// 它的作用是將 map 結(jié)果中那些 nil 的元素去除掉,這個操作通常會 “壓縮” 結(jié)果,讓其中的元素數(shù)減少,這也正是其名字中 compact 的來源
let compact = arr.compactMap({$0%2 == 0})
print(compact)
let arr: [String] = ["1", "2", "3", "cat", "5"]
arr.compactMap { Int($0)}.forEach{print($0)}
mapValues — 轉(zhuǎn)換value (Swift 4)
let dic: [String : Int] = [
"first": 1,
"second": 2,
"three": 3,
"four": 4
]
// 字典中的函數(shù), 對字典的value值執(zhí)行操作, 返回改變value后的新的字典
let mapValues = dic.mapValues({ $0 + 2 })
print(mapValues)
compactMapValues — 上面兩個的合并(Swift 5)
let dic: [String : String] = [
"first": "1",
"second": "2",
"three": "3",
"four": "4",
"five": "abc"
]
// 將上述兩個方法的功能合并在一起,返回一個對value操作后的新字典, 并且自動過濾不符合條件的鍵值對
let newDic = dic.compactMapValues({ Int($0) })
print(newDic)