Andrei Andrei - 7 months ago 13
Swift Question

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

New to Swift. I'm trying to use a switch on an

@IBAction
method, which is hooked to multiple buttons

i.e.

@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?!'

Answer

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
        }
    }
}