【问题标题】:Switching on UIButton title: Expression pattern of type 'String' cannot match values of type 'String?!'打开 UIButton 标题:“字符串”类型的表达式模式无法匹配“字符串?!”类型的值
【发布时间】:2016-08-17 06:58:03
【问题描述】:

我正在尝试在@IBAction 方法中使用开关,该方法与多个按钮挂钩

@IBAction func buttonClick(sender: AnyObject) {

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

当我尝试上述方法时,我收到以下错误:

“字符串”类型的表达式模式无法匹配类型的值 “字符串?!”

【问题讨论】:

  • switch (sender as! UIButton).currentTitle { 工作吗?
  • @EdCottrell 您可以直接在 Swift 中比较字符串,因为像 == 这样的测试测试是否相等,而 === 测试对象是否是相同的确切对象。
  • @EdCottrell 是的,以前用过,出于某种原因,我觉得开关会更干净,所以尝试一下。
  • 我只是给它们添加不同的标签值而不是读取它们的可选标题
  • 如果您对String?! 中的! 的来源感兴趣,请查看stackoverflow.com/questions/33388830/…

标签: ios swift types switch-statement pattern-matching


【解决方案1】:

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

【讨论】:

  • 感谢您的回答,但我现在收到Expression pattern of type 'String' cannot match values of type 'String?'
  • 别忘了提到它也只是因为你将方法参数从 AnyObject 更改为 UIButton
  • @Andrei 确保将发件人类型更改为UIButton
  • @Guig 可能是因为可选项实际上是枚举,所以它与开关的逻辑相混淆。如果您需要将非可选开关与可选开关进行比较,您仍然可以通过添加 ?到最后,例如case "Button1"?:
  • 但是您可以将它们与== 进行比较,并且 switch 是一回事,对吧?
【解决方案2】:

解开currentTitle 的另一种方式,我认为更优雅的方式是:

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

【讨论】:

    猜你喜欢
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    相关资源
    最近更新 更多