Swift?reduce函數使用示例詳解
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.
initialResultis passed tonextPartialResultthe 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
再來看一個示例:
// 統(tǒng)計下面的字符串中每個字符的使用次數
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]
其實就是遍歷字符串,然后把它們into到字典[:]中
還有個示例:http://www.dbjr.com.cn/article/279000.htm說的比較好直接粘過來:
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通過這些示例,再不懂,中午就不要吃飯了
以上就是Swift reduce函數使用示例詳解的詳細內容,更多關于Swift reduce函數的資料請關注腳本之家其它相關文章!
相關文章
Objective-C中的block與Swift中的尾隨閉包使用教程
Block是OC中的閉包,他和swift中的閉包有什么區(qū)別呢?下面這篇文章就來給大家介紹關于Objective-C中的block與Swift中的尾隨閉包使用的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下。2017-12-12

