在Swift 3中使用NSNumber&Integer值
我试图将我的项目转换为Swift 3.0,但我有两个错误消息时使用NSNumber
和Integers
。
不能指定typesint来键入NSNumber
对于
//item is a NSManaged object with a property called index of type NSNumber var currentIndex = 0 for item in self.selectedObject.arrayOfItems { item.index = currentIndex currentIndex += 1 }
甚至当我将currentIndex
更改为NSNumber
types,那么我得到的错误
二元运算符“+ =”不能用于input“NSNumber”和“Int”
所以然后我创build一个名为NSNumber
types的属性添加到currentIndex
但是,然后得到以下错误;
二元运算符'+ ='不能应用于两个NSNumber操作数
&第二个错误我得到的是
没有“+”候选产生预期的上下文结果typesNSNumber
let num: Int = 210 let num2: Int = item.points.intValue item.points = num + num2
在这里,我只是试图添加210点的属性值, item
是一个NSManagedObject
。
所以基本上我有问题让我的头添加数字的属性types的NSNumber
。 我正在使用NSNumber
因为它们是NSManagedObject
的属性。
谁能帮我吗 ? 我有80多个错误,都是上面提到的错误之一。
谢谢
在Swift 3之前,很多types在必要时自动“桥接”到某个NSObject
子类的实例,例如String
到NSString
,或Int
, Float
,…到NSNumber
。
从Swift 3开始,你必须明确地进行转换:
var currentIndex = 0 for item in self.selectedFolder.arrayOfTasks { item.index = currentIndex as NSNumber // <-- currentIndex += 1 }
或者,在创buildNSManagedObject
子类时使用“使用基本数据types的标量属性”选项,那么该属性具有一些整数types而不是NSNumber
,因此您可以在不进行转换的情况下获取并设置它。
你应该留下或原来的代码,只是改变任务,使其工作:
var currentIndex = 0 for item in self.selectedFolder.arrayOfTasks { item.index = NSNumber(integer: currentIndex) currentIndex += 1 }
由于你的代码在Swift 2中工作正常,我期望这是在下一次更新中可能会改变的行为。
在Swift 4中(在Swift 3中它可能是一样的) NSNumber(integer: Int)
被replace为NSNumber(value: )
,其中value
可以是几乎任何types的数字:
public init(value: Int8) public init(value: UInt8) public init(value: Int16) public init(value: UInt16) public init(value: Int32) public init(value: UInt32) public init(value: Int64) public init(value: UInt64) public init(value: Float) public init(value: Double) public init(value: Bool) @available(iOS 2.0, *) public init(value: Int) @available(iOS 2.0, *) public init(value: UInt)
Swift 4 :
var currentIndex:Int = 0 for item in self.selectedFolder.arrayOfTasks { item.index = NSNumber(value: currentIndex) // <-- currentIndex += 1 }