9

I'm trying to use a switch in an @IBAction method, which is hooked to multiple buttons

@IBAction func buttonClick(sender: AnyObject) {

        switch sender.currentTitle {
            case "Button1":
                print("Clicked Button1")
            case "Button2":
                print("Clicked Button2")
            default:
                break
        }

When I try the above, I get the following error:

Expression pattern of type 'String' cannot match values of type 'String?!'

jscs
  • 63,694
  • 13
  • 151
  • 195
Andrei
  • 2,607
  • 1
  • 23
  • 26

2 Answers2

14

currentTitle is an optional so you need to unwrap it. Also, the type of sender should be UIButton since you are accessing the currentTitle property.

@IBAction func buttonClick(sender: UIButton) {
    if let theTitle = sender.currentTitle {
        switch theTitle {
            case "Button1":
                print("Clicked Button1")
            case "Button2":
                print("Clicked Button2")
            default:
                break
        }
    }
}
Marc Khadpe
  • 2,012
  • 16
  • 14
  • Thanks for the answer, however I now get `Expression pattern of type 'String' cannot match values of type 'String?'` – Andrei Apr 23 '16 at 17:53
  • don't forget to mention also it only works because you changed the method parameter from AnyObject to UIButton – Leo Dabus Apr 23 '16 at 17:53
  • @Andrei Make sure to change the type of sender to `UIButton` – Marc Khadpe Apr 23 '16 at 17:57
  • @MarcKhadpe yep, missed that. Thanks. – Andrei Apr 23 '16 at 18:00
  • Why can't swift compare a `String` and a `String?` in a switch ? This looks stupid – Guig Oct 25 '16 at 20:46
  • 3
    @Guig Probably because optionals are actually enums, so it messes with the switch's logic. If you need to compare a non-optional to an optional switch, you can still do it by adding a ? to the end e.g. `case "Button1"?:` – John Montgomery Apr 05 '17 at 16:23
  • 1
    But you can compare them with `==` and switch is kind of the same thing right? – Guig Apr 05 '17 at 19:58
2

Another way of unwrapping currentTitle and I think a more elegant one is:

switch sender.currentTitle ?? "" { 
    //case statements go here
}
Vasil Garov
  • 4,851
  • 1
  • 26
  • 37