如何在Swift中将Int32转换为Int? [英] How can I convert Int32 to Int in Swift?

查看:1850
本文介绍了如何在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
}

这篇关于如何在Swift中将Int32转换为Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆