作者:so的青春 | 来源:互联网 | 2023-07-21 20:07
篇首语:本文由编程笔记#小编为大家整理,主要介绍了swift 在数组的每个元素上调用函数相关的知识,希望对你有一定的参考价值。
1. forEach(_:)
Calls the given closure on each element in the sequence in the same order as a for-in loop.
The two loops in the following example produce the same output:
let numberWords = ["one", "two", "three"]
numberWords.forEach { word in
print(word)
}
// "one"
// "two"
// "three"
Using the forEach method is distinct from a for-in loop in two important ways:
You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls.
Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won’t skip subsequent calls.
2. Map & CompactMap
let possibleNumbers = ["1", "2", "three", "///4///", "5"]
let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]
let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]
arr = [1,2,3]
print(arr.compactMap { $0/2 })