ios - 在 swift 中找到第一个正元素后退出循环

标签 ios swift loops

所以,需要你的帮助,我有循环,我想在其中找到第一个正元素,它将是标签文本并从所有循环中退出,但每次我得到最后一个元素时:

    for j in getArrayOfAllTimes[i].timeForGetDifference()
                {
                    switch j - timeNow() {

                    case let x where x > 0:
                        nextTimeLabel.text = String(j - timeNow())
                        break

                    default:

                        break  
                    }
}

如何获取第一个元素 > 0?

最佳答案

Arrayfirst(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

对于上面的示例,我们可以按如下方式设置 nextTimeLabeltext 属性,使用 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, an if statement, or a switch 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/

相关文章:

ios - 在不重新加载数据的情况下更改 UICollectionView 中的标签值?

ios - 如何保存使用 UIImagePickerController 相机拍摄的照片以便稍后在应用程序中显示?

python - 将 Python 搜索结果保存在变量中并使用其元素

ios - 使用 IOS9 时,无法在 UITable 节标题上的 UIButtons 上触发触摸事件(IOS10 没问题)

unix - 帮助Unix tar和grep循环

c++ - 迭代过程命名

iOS SDK : ARC removeFromSuperview

ios - UIImageView 中的矢量图像在 iOS 12 和 13 中呈现不同的方式

ios - 离开 iPhone 时在 Apple Watch 上记录和保存锻炼?

ios - 圆形 ImageView