JKSDEV JKSDEV - 2 months ago 11
Swift Question

Converting String value from UILabel to Int returns nil | Swift 2 / Xcode 7

I have a

UILabel
which contains a
String
value of a number, for example;

@IBOutlet weak var label: UILabel!

label.text = "5"


I am then trying to convert the string value to as an unwrapped Int constant. Previously I used
toInt
but that is now gone and I tried by doing,

let labelText: String = label.text!
let size: Int! = Int(labelText)


However size is returning a
nil
value instead of the converted value, in this case it should be a
Int
of value 5. Does anybody know where I am going wrong with the new syntax ?

Answer

The syntax you provided should work.

Maybe the label.text is set to be some other value that would make the conversion fail.

Here are some examples that would make size to be nil:

label.text = "5+"
label.text = "5.0"

Yes, even "5.0" would make the conversion fail.

Explicitly cast to Double and cast back to Int should work.

If you don't like to deal with the casting stuffs (or you don't know the format of the text), you may avoid it by using NSNumberFormatter, here's an example:

let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle

if let number = formatter.numberFromString(labelText) {
    // number is an instance of NSNumber
    size = number.integerValue
}

Please note that creating a NSNumberFormatter is a expensive operation, please cache it if possible.