在应该加载场景的按钮中,我正在尝试学习使用 guard
语句,但对它在四个“转义”中的每一个中所做的事情感到非常困惑。也不知道在没有场景的情况下应该怎么处理。
此处正确使用的是: continue
、return
、break
或 throw
?
还有……为什么?
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.location(in: self)
if self.rr.contains(location) {
guard let nextScene = goesTo
else {print(" No such Scene ")
continue } // continue, return, break, throw !!!!????
loadScene(withIdentifier: nextScene)
}
}
}
最佳答案
我认为场景不适合 guard 语句,因为你有很多情况在循环中,你想避免一些情况!首先我们需要知道什么时候应该使用 guard 语句。是的,它可以帮助您处理错误,但这并不意味着您应该随时随地使用它!
Why guard and when to use them and not to use them:
更新
我希望这能澄清你的问题
when you are using break
let array: [Int?] = [3, 7, nil, 12, 40]
for arrayValue in array {
guard let value = arrayValue else {
print("No Value")
break
}
print(value)
}
输出
3
7
没有值(value)
when you are using continue
let array: [Int?] = [3, 7, nil, 12, 40]
for arrayValue in array {
guard let value = arrayValue else {
print("No Value")
continue
}
print(value)
输出
3
7
没有值(value)
12
40
Return 将关闭该函数,并且在这种情况下与 break 的行为相同。现在请根据您的需要做出决定!如果您认为在没有场景条件时可以中断它,那么就中断,或者如果您想跳过它,那么只需继续跳过那个确切的场景。我希望你明白我的意思
关于swift - 如何在场景转换尝试中处理 "no scene"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41009980/