如何在Swift中将Int32转换为Int?
应该很容易,但我只能找到逆转换。
如何在Swift中将Int32转换为Int?
除非问题不同?
It should be easy but I can only find the reverse conversion. How can I convert Int32 to Int in Swift? Unless the problem is different?
我有一个存储在Core Data中的值,我希望将其作为Int返回。
I have a value stored in Core Data and I want to return it as an Int.
这是我正在使用的代码,它不起作用:
Here is the code I am using, which does not work:
func myNumber () -> Int {
var myUnit:NSManagedObject
myUnit=self.getObject("EntityName") // This is working.
return Int(myUnit.valueForKey("theNUMBER")?.intValue!)
}
错误是你的?在valueForKey之后。
The error is your ? after valueForKey.
Int初始值设定项不接受选项。
Int initializer doesnt accept optionals.
通过 myUnit.valueForKey (theNUMBER)?。intValue!
给你一个可选值和!最后没有帮助。
By doing myUnit.valueForKey("theNUMBER")?.intValue!
gives you an optional value and the ! at the end doesnt help it.
只需替换为:
return Int(myUnit.valueForKey("theNUMBER")!.intValue)
但你也可以这样做如果你希望它是安全的话,请这样:
But you could also do like this if you want it to be fail safe:
return myUnit.valueForKey("theNUMBER")?.integerValue ?? 0
为了缩短你的功能,你可以这样做:
And to shorten you function you can do this:
func myNumber() -> Int {
let myUnit = self.getObject("EntityName") as! NSManagedObject
return myUnit.valueForKey("theNUMBER")?.integerValue ?? 0
}