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.

  • UIView two animations coexisting
  • Cocoapods for development only
  • Scheduling A Task
  • no umbrella header found for target, module map will not be generated
  • What is the difference between outlet connection and action connection?
  • iOS rotate video AVAsset avfoundation
  • 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
        }
    }