如何在swift中将Int转换为int?

ppa*_*ica 5 ios swift

我有一个名为Int的类型的变量

var number = value!.integerValue as Int
Run Code Online (Sandbox Code Playgroud)

现在我必须使用该值创建一个NSNumber对象.

我正在尝试使用此构造函数

value = NSNumber(int: number)
Run Code Online (Sandbox Code Playgroud)

,但它不起作用.

它期望原始类型int,而不是Int我猜.

有谁知道怎么解决这个问题?

谢谢!

Dim*_*ima 6

你这样做 value = number

正如您在文档中看到的那样:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html

本机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
Run Code Online (Sandbox Code Playgroud)

Swift 3更新

在Swift 3中,这种桥接转换不再是自动的,你必须像这样明确地转换它:

let n = 42
let m: NSNumber = n as NSNumber
Run Code Online (Sandbox Code Playgroud)