本文内容基于Swift 4
在读《Swift进阶》的时候发现,Swift提供了很多内置的高阶函数用于数组变形,使用高阶函数最大优势在于,用更少量的代码去解决问题。
map
let a = [1,2,3,4,5,6]
如果要把这个数组中的元素每个都+1,按照以前的做法
var b = [Int]()
for ele in a {
b.append(ele+1)
}
print(b)//[2,3,4,5,6,7]
但使用map之后
let b = a.map { (ele) -> Int in
return ele+1
}
print(b)//[2,3,4,5,6,7]
同时也因为Swift
闭包的特性,上面的代码还可以写成
let b = a.map{
$0+1
}
print(b)//[2,3,4,5,6,7]
flatMap
flatMap
和map
的用法很相像,通过对比两者的不难发现:
public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
public func flatMap(_ transform: (Element) throws -> String?) rethrows -> [String]
flatMap
允许返回nil
值,对元素进行过滤再变形flatMap
可以将多维数组转成一维数组
let a = [[1,2,3],[4,5,6]]
let b = a.flatMap {
$0
}
print(b)//[1,2,3,4,5,6]
filter
filter
用于过滤元素
let a = [1,2,3,4,5,6]
//去掉a数组内<4的元素
let b = a.filter { (value) -> Bool in
return value > 4
}
print(b)
reduce
reduce
可以将数组中的元素合并到一个值
let a = [1,2,3,4,5,6]
//如果要将a数组内所有元素相加,再+7,以前的写法是这样:
let count = 0
for value in a {
count += value
}
count += 7
print(count)//28
在使用reduce之后,事件就变得非常简单
let b = a.reduce(7) { (count, value) -> Int in
return count+value
}
print(b)//28
sequence
通过sequence
可以生成无限的序列
假设我们要从遍历从0到100的偶数,以前的写法是:
for i in 0..<26 {
print(i*2) //0,2,4...48,50
}
而sequence
只需要:
for i in sequence(first: 0, next: {$0+2}) {
if i>50 {
break
}
print(i) //0,2,4...48,50
}
sorted
用于排序
//倒序
let a = [1,2,3,4,5,6]
let b = a.sorted { (next, last) -> Bool in
return next > last
}
print(b)//[6, 5, 4, 3, 2, 1]
//根据字母顺序倒序
let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let descendingStudents = students.sorted(by: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
split
分割数组
let a = [1,2,3,4,5,6]
//按照0分割数组,数组中没有0
let b = a.split(separator: 0)
print(b[0])//[1, 2, 3, 4, 5, 6]
let a = [1,2,3,4,3,6]
//按照3分割数组
let b = a.split(separator: 3)
print(b)//[ArraySlice([1, 2]), ArraySlice([4]), ArraySlice([6])]
prefix
prefix
和filter
类似,过滤条件为true的时候会到结果中,区别在于,当为false的时候会直接结束
let a = [1,2,3,4,3,6]
let b = a.prefix(upTo: 4)
print(b)//[1,2,3,4]
drop
drop
和prefix
相反,当为true的时候元素会被丢弃,为false的时候会直接结束
let a = [1,2,3,4,3,6]
let b = a.drop(while: { (value) -> Bool in
if value < 3 {
return true
}
return false
})
print(b)//[3, 4, 3, 6]
请保持转载后文章内容的完整,以及文章出处。本人保留所有版权相关权利。