Swift: using the switch statement in touchsBegan

I want to clean my touchesBegan(..)in SKScene. I wanted to make a case statement instead of my chain if .. else. However, I get errors in the implementation, which means 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 the code: after clicking, some clicks on the shortcuts work, but some others create an error Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode 0x0):

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
    }
}
+4
source share
3 answers

You can write a kind of odd but functional switchif you want behavior ===like this:

switch(true){
        case self.nodeAtPoint(location) === playLabel : buildLevelSelect()
        case self.nodeAtPoint(location) === aboutLabel : createAboutView()
        case self.nodeAtPoint(location) === storeLabel : createStore()
        default : break
}

-, , if-else.

+5

- .name , . , :

switch (self.nodeAtPoint(location).name ?? "") { 
    case "playLabel" :
        buildLevelSelect()
    case "aboutLabel" :
        ...
+4

You can also drop objects in a switch statement, and then your code works as expected

    if let touch = touches.first as UITouch! {

        let touchLocation = touch.location(in: self)

        switch self.atPoint(touchLocation) {
            case redBox as SKSpriteNode:
                print("touched redBox")
            case greenBox as SKSpriteNode:
                print("touched greenBox")
            default:
                print("touched nothing")
        }
    }
+3
source

Source: https://habr.com/ru/post/1671388/


All Articles