JKSDEV JKSDEV - 1 year ago 129
Swift Question

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

I have a

which contains a
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
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
value instead of the converted value, in this case it should be a
of value 5. Does anybody know where I am going wrong with the new syntax ?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download