打开UIButton标题:“String”类型的表达式模式不能匹配“String ?!”类型的值 [英] Switching on UIButton title: Expression pattern of type 'String' cannot match values of type 'String?!'

查看:292
本文介绍了打开UIButton标题:“String”类型的表达式模式不能匹配“String ?!”类型的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 @IBAction 方法中使用一个开关,它连接到多个按钮

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:


'String'类型的表达式模式不能匹配
'String的类型值!!'

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


推荐答案

currentTitle 是可选的,因此您需要打开它。此外,发件人的类型应为 UIButton ,因为您正在访问 currentTitle property。

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

这篇关于打开UIButton标题:“String”类型的表达式模式不能匹配“String ?!”类型的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆