ios - 开启 UIButton title : Expression pattern of type 'String' cannot match values of type 'String?!'

标签 ios swift types switch-statement pattern-matching

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

@IBAction func buttonClick(sender: AnyObject) {

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

当我尝试上述操作时,出现以下错误:

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

最佳答案

currentTitle 是可选的,因此您需要将其解包。此外,sender 的类型应该是 UIButton,因为您正在访问 currentTitle 属性。

@IBAction func buttonClick(sender: UIButton) {
    if let theTitle = sender.currentTitle {
        switch theTitle {
            case "Button1":
                print("Clicked Button1")
            case "Button2":
                print("Clicked Button2")
            default:
                break
        }
    }
}

关于ios - 开启 UIButton title : Expression pattern of type 'String' cannot match values of type 'String?!' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814250/

相关文章:

ios - 如何使用 StoryBoard 在 iPad 上的 Popover 中显示 UIDatePicker?

Swift 3 调用结果 (_ :parameters:completionHandler:)' is unused warning and Braced block of statements is an unused closure error

delphi - 如何将 int 转换为货币?

ios - swift 类 'nil' 中的所有值

ios - 选择 UITextField 时向上移动 UIView

ios - 已发布的 iOS 应用程序中的打印语句去哪里了?

c# - 私有(private)诠释? _城市_Id;谁能告诉我 "?"在这里是什么意思

Python 2/3 : Why is type(Foo. __init__) 不同?

javascript - Realm + React Native 最佳实践用户设置与同步

ios - 如何用阴影,填充和圆角样式化tableview部分?