【问题标题】:Swift Break loop for if statement trueif 语句为 true 的 Swift Break 循环
【发布时间】:2018-02-23 16:48:50
【问题描述】:

这基本上是代码询问。

for obj in objList {

    if otherObjList.contains(where: { $0.localString == obj.localString}) {
       //if this statement true, I wanna break this statement and 
       //continue loop on the above list (objList)
     } 

}

我试过了,如果语句为真,它仍然会尝试在 otherObjList 上完成循环。顺便说一句,我想在声明为真时打破这一点,并为 objList 继续循环。

【问题讨论】:

  • 找到对象时使用break。 @rmaddy 我认为是break
  • @rmaddy - 你不是说break吗?
  • 是的,我想打破该语句并继续循环 objList。 @TedHopp
  • @TedHopp break 将退出循环
  • @rmaddy 对不起,如果我错了,但是;它仍在尝试在 otherObjList 上完成循环。顺便说一句,我想 break 当语句为 true 并为 objList 继续循环。

标签: swift


【解决方案1】:

听起来你只是想要这个:

for obj in objList {

    if otherObjList.contains(where: { $0.localString == obj.localString }) {
        continue
    }

    // Statements here will not be executed for elements of objList
    // that made the above if-condition true. Instead, the for loop
    // will execute from the top with the next element of objList.
}

【讨论】:

  • 它在我的测试中有效。如果您需要更多帮助,您需要发布错误的详细信息。
【解决方案2】:

你似乎在寻找continue

这是continuebreak 之间区别的简单示例:

// break
// Prints 1,2,3,4,5
for i in 1 ... 10 {
    print(i, terminator: "")
    if i == 5 {
        break
    }
    print(",", terminator: "")
}
print()

// continue
// Prints 1,2,3,4,56,7,8,9,10,
for i in 1 ... 10 {
    print(i, terminator: "")
    if i == 5 {
        continue
    }
    print(",", terminator: "")
}
print()

简而言之,break 立即离开周围的循环,而continue 中止当前迭代并在下一次迭代中继续循环。

【讨论】:

  • 以确保我在“loop for”中的陈述与您的解释不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2014-02-21
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
  • 2022-05-21
相关资源
最近更新 更多