Swift:UIButton textLabel.text值在switch语句中不可用 [英] Swift: UIButton textLabel.text value not useable in switch statement

查看:172
本文介绍了Swift:UIButton textLabel.text值在switch语句中不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift和iOS开发的新手,因此我正尝试构建一个用于学习目的的计算器应用程序.但是,我遇到了一个错误.我已经用它们代表的数字为所有按钮加上了标题,因此我正在通过sender.titleLabel.text检索buttonPress IBAction中的标题.然后,将其传递给switch语句,以确定按钮是数字还是运算符.

I am new to Swift and iOS development, so I am trying to build a calculator app for learning purposes. However, I am encountering an error. I have titled all of my buttons with the number they represent, so I am retrieving the title in the buttonPress IBAction via sender.titleLabel.text. Then, I pass that into a switch statement to determine if the button was a number or an operator.

func handleButton (sender:UIButton) {
switch sender.titleLabel.text {
case "1","2","3","4","5","6","7","8","9","0" :
    println(sender.titleLabel.text)
default:
    break
    }     
}

错误是sender.titleLabel.text不会绑定到我输入的字符串值-也不会绑定到任何字符串值-即使它的类型为String.

The error is that sender.titleLabel.text will not bind to the string values I have entered - nor any string values - even though it is is of type String.

推荐答案

在编译器中似乎存在一个错误,即在switch语句中不能使用隐式解包的Optionals.相反,您可以使用可选绑定来满足编译器的要求.另外,这将处理titleLabel.text为nil的情况.

There seems to be a bug in the complier at the moment where Implicitly Unwrapped Optionals cannot be used in switch statements. Instead you can use optional binding to satisfy the compiler. As an extra plus, this will handle the case where titleLabel.text is nil.

func handleButton (sender:UIButton) {
    if let text = sender.titleLabel.text {
        switch text {
            case "1","2","3","4","5","6","7","8","9","0" :
                println(sender.titleLabel.text)
            default:
                break
        }
    }
    else {
        // sender.titleLabel.text is nil
    }
}

这篇关于Swift:UIButton textLabel.text值在switch语句中不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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