I want to clean up my touchesBegan(..)
in SKScene
. I wanted to make a case statement instead of my if .. else
chain. However, I get errors when implementing, which suggests that I don't know how equality is done under the hood.
Before code:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if self.nodeAtPoint(location) === playLabel {
buildLevelSelect()
} else if self.nodeAtPoint(location) === aboutLabel {
createAboutView()
} else if self.nodeAtPoint(location) === storeLabel {
createStore()
}
}
}
After code: After clicking around, some label clicks work, but some others raise a Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode 0x0)
error:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
switch(self.nodeAtPoint(location)){
case playLabel :
buildLevelSelect()
case aboutLabel :
createAboutView()
case storeLabel :
createStore()
default : break
}
}
You can write a sort of odd looking but functional switch
if you want the ===
behavior as follows:
switch(true){
case self.nodeAtPoint(location) === playLabel : buildLevelSelect()
case self.nodeAtPoint(location) === aboutLabel : createAboutView()
case self.nodeAtPoint(location) === storeLabel : createStore()
default : break
}
In my opinion, this is still cleaner looking than the if-else chain.
The easiest way to accomplish this would be by populating the .name
property of your nodes, so then you could switch on the name instead. So then your switch would look like this:
switch (self.nodeAtPoint(location).name ?? "") {
case "playLabel" :
buildLevelSelect()
case "aboutLabel" :
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With