在swift中停止块文字的任何方法
像下面一样,我想通过类似于在swift中停止块文字的任何方法,swift,Swift,像下面一样,我想通过类似于break var numbers = [1,2,3,4] numbers.forEach { if $0 % 2 == 0 { break } } forEach不是循环(它是传递给循环的块,但不是循环本身),或者更准确地说,forEach不是Swift控制流的一部分。这就是为什么不能使用中断或继续 只需使用for in循环。 示例: var numbers = [ 1,2,3,4] func firstEvenNumber(in
break
var numbers = [1,2,3,4]
numbers.forEach {
if $0 % 2 == 0 {
break
}
}
forEach
不是循环(它是传递给循环的块,但不是循环本身),或者更准确地说,forEach
不是Swift控制流的一部分。这就是为什么不能使用中断
或继续
只需使用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
您可以在
forEach
闭包内使用return
,但它不会中断循环,只返回当前过程中的块
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]
该文件已作了解释
/// - 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.
但是你想试试这个
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)
}
}
}
由于要在第一次匹配时停止,因此应使用
first
而不是forEach
:
numbers.first { (number) -> Bool in
return number % 2 == 0
}
对结果进行处理(列表中的第一个偶数):
奖励:使用过滤器创建所有偶数的列表
:
let allEvenNumbers = numbers.filter { $0 % 2 == 0 }
你想做什么?举个例子,我只想控制流量。我解决了。请看,您还可以抛出一个例外。如果您只是尝试检查所有数字,您可以使用.allsusfit或.contains(其中:在数组上。实际上,在第二个示例中,“return”不起任何作用。删除它,结果将是相同的。要查看它在foreach中的工作方式,请尝试以下操作:inArray.foreach{if$0%2!=0{return}匹配。append($0)}@Aleksandr这正是重点。
return
在forEach
中可用,但没有OP想要的效果。所以使用:[y enumerateObjectsUsingBlock:^(id x,NSUInteger index,BOOL*stop){}];:)我的答案不是要提供一个黑客解决方案,有很多。我试图解释为什么它没有按照OP预期的方式工作,并提供一种惯用的方式来实现想要的结果。当然,我理解。上次只是个玩笑。但我注意到,您的代码只显示了return不能像预期的那样工作(顺便说一句,OP-btw不希望使用return),它没有显示它是如何工作的。示例中的Return不起任何作用。它从迭代中返回,无论如何都将在迭代后“结束”。我不想吵架或聊天,祝你有一个愉快的一天。
let allEvenNumbers = numbers.filter { $0 % 2 == 0 }