Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Using switch statement in touchesBegan

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
    }
}
like image 497
cdpalmer Avatar asked Dec 14 '22 00:12

cdpalmer


2 Answers

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.

like image 72
Daniel Legler Avatar answered Dec 27 '22 12:12

Daniel Legler


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" :
        ...
like image 29
creeperspeak Avatar answered Dec 27 '22 11:12

creeperspeak