ios – 在Swift 3中使用NSNumber和Integer值

我正在将我的项目转换为 Swift 3.0,但是在使用NSNumber和Integer时,我有两个错误消息.

Cannot assign type int to type 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类型,那么我得到错误

Binary operator ‘+=’ cannot be applied to type ‘NSNumber’ and ‘Int’

所以我创建一个名为NSNumber类型的属性来添加到currentIndex,但是会得到以下错误;

Binary operator ‘+=’ cannot be applied to two NSNumber operands

&安培;&安培;我得到的第二个错误是

No ‘+’ candidates produce the expected contextual result type NSNumber

let num: Int = 210
 let num2: Int = item.points.intValue
 item.points = num + num2

这里我只是试图添加210到点属性值,item是一个NSManagedObject.

所以基本上我有问题让我的头围绕NSNumber类型的属性添加数字.我正在使用NSNumber,因为它们是NSManagedObject的属性.

谁能帮我吗 ?我有超过80个错误,都是上述错误之一.

谢谢

解决方法

在Swift 3之前,许多类型被自动“桥接”到一个
某些NSObject子类的实例在必要的情况下,例如String to
NSString,或Int,Float,…到NSNumber.

从Swift 3开始,您必须明确表示:

var currentIndex = 0
for item in self.selectedFolder.arrayOfTasks {
   item.index = currentIndex as NSNumber // <--
   currentIndex += 1
}

或者,在创建NSManagedObject子类时,使用选项“使用原始数据类型的标量属性”那么该属性有一些整数类型而不是NSNumber,以便您无需转换即可获得和设置.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...