switch on location in touchesBegan ?

I was trying to make a nice compact switch statement for use inside touchesBegan in a SpriteKit based game.

something like this:-


            let location = touch.location(in: self)        

            switch location {
            case button1.position : gamePlayScene()
            case button2.position : settingsScene()
            case button3.position : highScoreScene()
            default : break
            }          


but it doesn't work 😟


trying to achieve the same as:


            if self.atPoint(location) == button1 {
                gamePlayScene()
            }
            if self.atPoint(location) == button2 {
                settingsScene()
            }
            if self.atPoint(location) == button3 {
                highScoreScene()
            }


is my syntax totally wrong or is it just not possible?


thanks!

Replies

, , Is button1 an UIButton ?


Where do you get the position property ?


In anycase, position is probably a rect, not a point, so your case comparison won't work.


You could test by adding a print statement to see what happens


            let location = touch.location(in: self)     
            Swift.print(location, button1.position, button2.position, button3.position)
            switch location {
                 case button1.position : gamePlayScene()
                 case button2.position : settingsScene()
                 case button3.position : highScoreScene()
                 default : break
            }
switch
statements do their comparison via the pattern match operation (
~=
). If you implement that operator for the types in play here, you’ll be able to use a
switch
statement.

The Swift Programming Language has an example of this.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"