Switching on UIButton title: Expression pattern of type 'String' cannot match values of type 'String?!'

狂风中的少年 提交于 2019-12-21 09:07:44

问题


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


回答1:


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



回答2:


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

switch sender.currentTitle ?? "" { 
    //case statements go here
}


来源:https://stackoverflow.com/questions/36814250/switching-on-uibutton-title-expression-pattern-of-type-string-cannot-match-va

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!