简体   繁体   English

将字符串值从UILabel转换为Int将返回nil | Swift 2 / Xcode 7

[英]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; 我有一个UILabel ,其中包含一个数字的String值,例如;

@IBOutlet weak var label: UILabel!

label.text = "5"

I am then trying to convert the string value to as an unwrapped Int constant. 然后我尝试将字符串值转换为未包装的Int常量。 Previously I used toInt but that is now gone and I tried by doing, 以前我习惯toInt但现在已经不见了,我试着这样做,

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 ? 但是大小返回的是nil值而不是转换后的值,在这种情况下,它应该是值为5的Int 。有人知道新语法出错了吗?

The syntax you provided should work. 您提供的语法应该有效。

Maybe the label.text is set to be some other value that would make the conversion fail. 也许label.text被设置为一些其他值会导致转换失败。

Here are some examples that would make size to be nil : 以下是一些使size nil示例:

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

Yes, even "5.0" would make the conversion fail. 是的,即使是“5.0”也会导致转换失败。

Explicitly cast to Double and cast back to Int should work. 显式地转换为Double并强制转换为Int应该可以工作。

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: 如果您不喜欢处理这些内容(或者您不知道文本的格式),可以使用NSNumberFormatter来避免它,这是一个例子:

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. 请注意,创建NSNumberFormatter是一项昂贵的操作,请尽可能缓存它。

let size = Int(labelText.text) - Int let size = Int(labelText.text) - Int

let dsize = Double(labelText.text) - double 让dsize = Double(labelText.text) - 加倍

You might have to unwrap the label if you want to use it with in a later func. 如果要在稍后的函数中使用它,则可能必须解开标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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