如下所示,我想通过类似的东西来阻止字面意思 break
var numbers = [1,2,3,4]
numbers.forEach {
if $0 % 2 == 0 {
break
}
}
Run Code Online (Sandbox Code Playgroud)
R M*_*nke 85
forEach不是循环(它是传递给循环的块,而不是循环本身),或者更确切地说,forEach不是Swift 控制流的一部分.这就是为什么你不能使用break或continue.
只需使用for-in循环.
示例:
var numbers = [ 1,2,3,4]
func firstEvenNumber(inArray array: [Int]) -> Int? {
var firstMatch : Int?
for number in numbers {
if (number % 2) == 0 {
firstMatch = number
break
}
}
return firstMatch
}
firstEvenNumber(inArray: numbers) // 2
Run Code Online (Sandbox Code Playgroud)
你可以return在forEach闭包内部使用,但它不会破坏循环,它只返回当前传递中的块.
var numbers = [ 1,2,3,4]
func evenNumbers(inArray: [Int]) -> [Int] {
var matches : [Int] = []
numbers.forEach{
if $0 % 2 == 0 {
matches.append($0)
// early return on even numbers
// does not stop forEach
// comparable to a continue in a for in loop
return
}
// only reached on uneven numbers
}
return matches
}
evenNumbers(numbers) // [2,4]
Run Code Online (Sandbox Code Playgroud)
Zap*_*ndr 17
由于您想在第一场比赛中停止,您应该使用first而不是forEach:
numbers.first { (number) -> Bool in
return number % 2 == 0
}
Run Code Online (Sandbox Code Playgroud)
对结果做一些事情(列表中的第一个偶数):
if let firstEvenNumber = numbers.first(where: { $0 % 2 == 0 }) {
print("The first even number on the list is \(firstEvenNumber)")
}
Run Code Online (Sandbox Code Playgroud)
奖励:使用以下方法创建所有偶数的列表filter:
let allEvenNumbers = numbers.filter { $0 % 2 == 0 }
Run Code Online (Sandbox Code Playgroud)
xu *_*ong 10
该文件已经解释过.
/// - Note: You cannot use the `break` or `continue` statement to exit the
/// current call of the `body` closure or skip subsequent calls.
/// - Note: Using the `return` statement in the `body` closure will only
/// exit from the current call to `body`, not any outer scope, and won't
/// skip subsequent calls.
Run Code Online (Sandbox Code Playgroud)
但是你想尝试一下.
extension CollectionType {
/// Use as
///
/// let num = [1,2,3,4,5]
/// num.forEach{
/// if $1 > 3 { $2 = true }
/// print($0,$1)
/// }
func forEach(body: ((Self.Generator.Element, Int, inout Bool) -> Void)) {
var stop = false
let enumerate = self.enumerate()
for (index,value) in enumerate {
if stop { break }
body(value,index,&stop)
}
}
/// Use as
///
/// let num = [1,2,3,4,5]
/// num.forEach{
/// if $0 > 3 { $1 = true }
/// print($0)
/// }
func forEach(body: ((Self.Generator.Element, inout Bool) -> Void)) {
var stop = false
for value in self {
if stop { break }
body(value,&stop)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25282 次 |
| 最近记录: |