简体   繁体   中英

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 ?

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.

let size = Int(labelText.text) - Int

let dsize = Double(labelText.text) - double

You might have to unwrap the label if you want to use it with in a later func.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM