1. 排序函数
func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]
var names: [String] = ["61","95","8","248","42"]
//一个包含字符串的数组
names = names.sorted(by: { (s1, s2) -> Bool in
return s1 < s2
})
print(names) //输出结果
该高阶函数内部大概实现:
extension Array {
typealias IncreasingOrder = (String,String) -> Bool
mutating func mySorted(_ increasingOrder:IncreasingOrder) -> [String] {
var newString:[String] = [String]()
// 假设这里采用简单选择排序
for n in 0..<self.count{
var tamper:String = self[n] as! String
for i in n+1..<self.count { //
var next:String = self[i] as! String
guard !increasingOrder(tamper,next) else {
continue
}
swap(&tamper, &next)
swap(&self[n], &self[i])
}
newString.append(tamper)
}
return newString
}
}
2. First函数
func first(where predicate: (Element) throws -> Bool) rethrows -> Element?
let names:[String] = ["61","95","8","248","42"]
//第一个满足条件的值
let name = names.first { (first) -> Bool in
return first == "8"
}!
print(name) // 输出: 8
3. Map函数
func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
var names:[String] = ["61","95","8","248","42"]
// 在每个字符前加上$
names = names.map { (str) -> String in
"$" + str
}
print(names) // ["$61", "$95", "$8", "$248", "$42"]
4. compactMap函数
flatMap 方法同 map 方法比较类似,只不过它返回后的数组中不存在 nil(自动把 nil 给剔除掉),同时它会把 Optional 解包
let array = ["Apple", "Orange", "Grape", ""]
let arr1 = array.map { a -> Int? in
let length = a.count
guard length > 0 else { return nil }
return length
}
print("arr1:\(arr1)") // [Optional(5), Optional(6), Optional(5), nil]
let arr2 = array.compactMap { a-> Int? in
let length = a.count
guard length > 0 else { return nil }
return length
}
print("arr2:\(arr2)")// [5, 6, 5]
5. filter函数
筛选满足条件的数据
var names:[String] = ["61","95","8","248","42"]
names = names.filter({ (str) -> Bool in
return str.count > 1
})
print(names) // ["61", "95", "248", "42"]
6. reduce函数
计算, 可以对数组中的元素进行计算
let array = [1, 2, 3, 4]
//计算数组array元素的和
//在这里$0和$1的意义不同,$0代表元素计算后的结果,$1代表元素
//0代表初始化值,在这里可以理解为 $0初始值 = 0
let result = array.reduce(0){
$0 + $1
}
print(result) // 10