所以,需要你的帮助,我有循环,我想在其中找到第一个正元素,它将是标签文本并从所有循环中退出,但每次我得到最后一个元素时:
for j in getArrayOfAllTimes[i].timeForGetDifference()
{
switch j - timeNow() {
case let x where x > 0:
nextTimeLabel.text = String(j - timeNow())
break
default:
break
}
}
如何获取第一个元素 > 0?
最佳答案
Array
的 first(where:)
方法
当找到满足 som 谓词的第一个元素时,您可以简单地使用 Array
方法 first(where:)
,而不是显式地跳出循环。 .
由于您尚未向我们提供minimal, complete and verifiable example (你应该这样做)我们将构建这样一个示例:
/* Example setup */
struct Foo: CustomStringConvertible {
private let bar: Int
init(_ bar: Int) { self.bar = bar }
func timeForGetDifference() -> Int {
return bar
}
var description: String {
return String(bar)
}
}
func timeNow() -> Int { return 10 }
let getArrayOfAllTimes = [Foo(6), Foo(2), Foo(9), Foo(4), Foo(11), Foo(3), Foo(13)]
// nextTimeLabel: some UILabel
对于上面的示例,我们可以按如下方式设置 nextTimeLabel
的 text
属性,使用 first(where:)
来找到满足我们的谓词的第一个元素(假设它存在)(否则将返回 nil,在这种情况下我们不会输入下面的可选绑定(bind) block )。
if let firstNonNegativeFoo = getArrayOfAllTimes
.first(where: { $0.timeForGetDifference() - timeNow() > 0 }) {
nextTimeLabel.text = String(describing: firstNonNegativeFoo) // 11
}
至于为什么您自己的方法不能按预期工作:switch
语句中的 break
语句将简单地结束 switch 的执行
语句(不是位于 switch
语句之上一级的循环。
来自Language Reference - Statements :
Break Statement
A
break
statement ends program execution of a loop, anif
statement, or aswitch
statement.
在您的情况下,您已添加 break
语句作为每个 case
的最后一个语句:这里,特别是 break
具有确实没有效果(因为 switch
语句无论如何都会在退出它进入的 case
后中断)。
for i in 1...3 {
switch i {
case is Int: print(i); break // redundant 'break'
case _: ()
}
} // 1 2 3
// ... the same
for i in 1...3 {
switch i {
case is Int: print(i)
case _: ()
}
} // 1 2 3
关于ios - 在 swift 中找到第一个正元素后退出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41822274/