In a button that's supposed to load a scene, I'm trying to learn to use a a guard
statement, but pretty baffled by what it does in each of its four "escapes". And don't know what I'm supposed to do with regards handling the situation where there's no scene.
Which is the correct to use here: continue
, return
, break
or throw
?
And... why?
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)
}
}
}
If you are in a for loop then continue
will move to the next iteration, while break
will exit the for loop. Return
will always exit the current function.
In this case you would want to put the guard statement before the for loop and exit touchesEnded, since I presume goesTo
is set elsewhere.
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let nextScene = goesTo else {
print(" No such Scene ")
return // exit touchesEnded since goesTo is not defined
}
for touch: AnyObject in touches {
let location = touch.location(in: self)
if self.rr.contains(location) {
loadScene(withIdentifier: nextScene)
}
}
}