reduce
Swift中数组的reduce
方法用于做序列元素的累加,如数组元素的累加, 函数原型:
@inlinable public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
参数:
- initialResult: 初始值, The value to use as the initial accumulating value.
initialResult
is passed tonextPartialResult
the first time the closure is executed. - nextPartialResult: 下一次累加的基准值
示例:
var arr = [1, 2, 3, 4, 5, 6, 7, 8]
/// initialResult: Result 初始值;
/// nextPartialResult:(Result, Int) 下一轮计算值, Result = initialResult + Int
/// Result是每轮计算的返回值(结果), Int 是数组元素
/// -> Result 返回值
/// `arr.reduce(initialResult: Result, nextPartialResult: (Result, Int) throws -> Result(Result, Int) throws -> Result>)`
var sum = arr.reduce(100) { partialResult, value in
print("\(value) --> \(partialResult)")
return partialResult + value // return 可省略
}
// 初始值是100,第一步就是:
// 100 + 1
// 再把2加上 --> 100 + 1 + 2
// 再把3加上 --> 100 + 1 + 2 + 3
// ...
print(sum) // 136
当然,也有好吃的语法糖,效果是一样的:
sum = arr.reduce(100) {
$0 + $1
}
print(sum)
reduce(into:)
reduce(into:)
方法也是一个实用方法,主要作用是遍历数组中的元素,把它们into到另一个对象中,示例:
如下有一个数组,把偶数放一个数组中,把奇数放一个数组中:
let nums = [1,2,3,4,5]
let result = nums.reduce(into: [[],[]]) { arr, num in
arr[num%2].append(num)
}
print(result[0]) // [2, 4]
print(result[1]) // [1, 3, 5]
这里into:后面的[[], []]是一个二级数组,这个二维数组即闭包中的arr, 而闭包中的num是nums数组中每一个值,遍历后把这个二维数组返回 (由函数原型的inout可知,返回的其实就是into:参数,本例中即二维数组)
func reduce<Result>(into: Result, _ updateAccumulatingResult: (inout Result, Element) throws -> ()) -> Result
为了更方例理解,展开为:
temp[1].append(1) //1%2 = 1/2 left 1 [[][1]]
temp[0].append(2) //2%2 = 2/2 left 0 [[2][1]]
temp[1].append(3) //3%2 = 3/2 = 1 left 1 [[2][1,3]]
temp[0].append(4) //4%2 = 4/2 left 0 [[2,4][1,3]]
temp[1].append(5) //5%2 = 5/2 = 2 left 1 [[2,4][1,3,5]]
示例参考:https://stackoverflow.com/questions/62103658/how-do-you-use-reduceinto-in-swift
再来看一个示例:
// 统计下面的字符串中每个字符的使用次数
let letters = "abracadabra"
let letterCount = letters.reduce(into: [:]) { counts, letter in
counts[letter, default: 0] += 1
}
print(letterCount) // ["a": 5, "r": 2, "c": 1, "b": 2, "d": 1]
Screen Shot 2022-12-30 at 18.55.05.png
其实就是遍历字符串,然后把它们into到字典[:]中
还有个示例:https://juejin.cn/post/7066782801928044581
说的比较好直接粘过来:
struct Person {
enum Gender {
case male
case female
}
var name = ""
var age = 0
var gender = Gender.female
}
let dataSource = [Person(name: "鸡大宝", age: 38, gender: .male),
Person(name: "江主任", age: 50, gender: .female),
Person(name: "可乐", age: 10, gender: .female),
Person(name: "伍六七", age: 16, gender: .male),
Person(name: "梅花十三", age: 20, gender: .female)]
// 获取数据源中男女各多少人
let genderCount = dataSource.reduce(into: [Person.Gender: Int]()) { result, person in
result[person.gender, default: 0] += 1
}
let maleCount = genderCount[Person.Gender.male] // 2
let femaleCount = genderCount[Person.Gender.female] // 3
print(maleCount ?? 0) // 2
print(femaleCount ?? 0) // 3
通过这些示例,再不懂,中午就不要吃饭了
网友评论