2 Replies
      Latest reply: Feb 11, 2017 3:07 PM by eskimo RSS
      squillop Level 1 Level 1 (0 points)

        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!

        • Re: switch on location in touchesBegan ?
          Claude31 Level 4 Level 4 (825 points)

          , , 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
                      }
          
          • Re: switch on location in touchesBegan ?
            eskimo Apple Staff Apple Staff (6,310 points)

            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"