Swift 常用高阶函数
- map函数
-
- 对每一个元素进行运算
- 计算每一个元素的count
- 对元素进行大小写变换
- 转换类型
- sorted函数
-
- flatMap函数
-
- filter函数
-
- 挑选count > 3的元素
- 挑选出大于0的元素
- 组合判断,挑选出大于0的元素,并排序
- reduce函数
-
map函数
对每一个元素进行运算
var values = [1, 2, 3]
values = values.map({ element in
element + 10
})
print(values)
计算每一个元素的count
let strings = ["one", "two", "three"]
let count = strings.map({ element in
element.count
})
print(count)
对元素进行大小写变换
var words = ["C", "D", "F", "A"]
words = words.map({ element in
element.lowercased()
})
print(words)
words = words.map({ element in
element.uppercased()
})
print(words)
转换类型
let values2 = [1, 2, 3]
let strings2 = values2.map {
String($0)
}
print(strings2)
let intArr = strings2.map({
Int($0)
})
print(intArr)
let floatArr = strings2.map({
Float($0)
})
print(floatArr)
sorted函数
从小到大排序
let strings3 = [1, 10, 12, 5, 7, -5]
let value1 = strings3.sorted(by: <)
print(value1)
从大到小排序
let value2 = strings3.sorted(by: >)
print(value2)
flatMap函数
降维
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = [7, 8, 9]
let value = [arr1, arr2, arr3]
print(value)
let flatMapArr = value.flatMap( {$0} )
print(flatMapArr)
过滤元素类型
let varietyTypeArr = ["str", "4", "8", "str2"]
let strArr = varietyTypeArr.flatMap { element in
return Int(element)
}
print(strArr)
let compactMapArr = varietyTypeArr.compactMap { element in
return Int(element)
}
print(compactMapArr)
filter函数
挑选count > 3的元素
let strs = ["one", "A", "C", "two", "three", "four"]
let ret1 = strs.filter( {$0.count > 3} )
print(ret1)
let values = [1, 10, 12, 5, 7, -5]
let ret2 = values.filter( {$0 > 0} )
print(ret2)
let ret3 = values.filter( {$0 > 0} ).sorted(by: >)
print(ret3)
挑选出大于0的元素
let values = [1, 10, 12, 5, 7, -5]
let ret2 = values.filter( {$0 > 0} )
print(ret2)
组合判断,挑选出大于0的元素,并排序
let ret3 = values.filter( {$0 > 0} ).sorted(by: >)
print(ret3)
reduce函数
拼接元素
let strs = ["one", "two", "three"]
let ret = strs.reduce("to") { (result, element) -> String in
return element + result
}
print(ret)
计算元素字符个数
let count = strs.reduce(0) { partialResult, element in
return partialResult + element.count
}
print(count)
let letters = "aabbbccccddddddeeed"
let letterCount = letters.reduce(into: [:]) { counts, letter in
counts[letter, default: 0] += 1
}
print(letterCount)
求和
let values = [1, 10, 12, 5, 7, -5]
let sums = values.reduce(0, +)
print(sums)