Swift: UIButton textLabel.text value not useable in switch statement

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

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.

  • How to Put a static UIButton Overlaying a UITableView
  • Overlay an UIButton over an UIWebView in Swift
  • My Custom Button is not getting click in iCarousel iOS?
  • How do I replicate the iOS keyboard appearance?
  • Display image and text in Button
  • Custom Button frame doesn't look as good as Round Rect UIButton
  • Solutions Collect From Internet About “Swift: UIButton textLabel.text value not useable in switch statement”

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