gpt4 book ai didi

ios - 如何快速将 Int 转换为 int?

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:44 28 4
gpt4 key购买 nike

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

var number = value!.integerValue as Int

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

我正在尝试使用这个构造函数

value = NSNumber(int: number)

,但它不起作用。

它需要原始类型 int,我猜不是 Int。

有人知道如何解决这个问题吗?

谢谢!

最佳答案

你只需做 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

Swift 3 更新

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

let n = 42
let m: NSNumber = n as NSNumber

关于ios - 如何快速将 Int 转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30060356/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com