[英]How to convert Int to int in swift?
I have a variable called number of type Int 我有一个名为Int的类型的变量
var number = value!.integerValue as Int
Now I have to create a NSNumber object using that value. 现在我必须使用该值创建一个NSNumber对象。
I am trying to use this constructor 我正在尝试使用此构造函数
value = NSNumber(int: number)
, but it does not work. ,但它不起作用。
It expect the primitive type int, not Int I guess. 它期望原始类型int,而不是Int我猜。
Anyone know how to get around this? 有谁知道怎么解决这个问题?
Thanks! 谢谢!
You just do value = number
你只做
value = number
As you can see in the documentation: 正如您在文档中看到的那样:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html
the native swift number types generally bridge directly to NSNumber
. 本机swift数字类型通常直接桥接到
NSNumber
。
Numbers
Swift automatically bridges certain native number types, such as Int and Float, to NSNumber. This bridging lets you create an NSNumber from one of these types:
SWIFT
let n = 42
let m: NSNumber = n
It also allows you to pass a value of type Int, for example, to an argument expecting an NSNumber. Note that because NSNumber can contain a variety of different types, you cannot pass it to something expecting an Int value.
All of the following types are automatically bridged to NSNumber:
Int
UInt
Float
Double
Bool
Swift 3 update Swift 3更新
In Swift 3, this bridging conversion is no longer automatic and you have to cast it explicitly like this: 在Swift 3中,这种桥接转换不再是自动的,你必须像这样明确地转换它:
let n = 42
let m: NSNumber = n as NSNumber
The issue is because in ObjC, an int
is a 32 bit number, and an integer
or NSInteger
is a 64 bit number. 问题是因为在ObjC中,
int
是32位数,而integer
或NSInteger
是64位数。
var number = value!.integerValue as Int
Number is of type Int
which corresponds to the ObjC type NSInteger
Number是
Int
类型,对应于ObjC类型NSInteger
You now try to create with this: 您现在尝试使用此创建:
value = NSNumber(int: number)
Which takes an Int32
or int
type, thus resulting in failure. 采用
Int32
或int
类型,从而导致失败。 You have a few options that will work. 你有一些选择可行。
One: 一:
value = NSNumber(int: Int32(number))
Two (probably better): 两个(可能更好):
value = NSNumber(integer: number)
Three (probably best): 三(可能最好):
As @Dima points out, you can just set it directly because swift automatically converts: 正如@Dima指出的那样,您可以直接设置它,因为swift会自动转换:
value = number
对于Swift 3,你必须使用:
var convertedNumber = NSNumber(value: numberToConvert)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.