使用NSNumber& Swift 3中的整数值 [英] Working with NSNumber & Integer values in Swift 3
问题描述
我正在尝试将我的项目转换为Swift 3.0,但是当使用 NSNumber
和整数$ c $时,我有两条错误消息C>。
I am trying to convert my project to Swift 3.0 however I am having two error messages when working with NSNumber
and Integers
.
无法将类型int指定为类型NSNumber
Cannot assign type int to type NSNumber
for
//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
然后我收到错误
and even when I change currentIndex
to a type NSNumber
then I get the error
二进制运算符'+ ='不能应用于'NSNumber'和'Int'
Binary operator '+=' cannot be applied to type 'NSNumber' and 'Int'
然后我创建一个名为的属性类型
NSNumber
添加到 currentIndex
但是然后得到以下错误;
so then I create a property called one
of type NSNumber
to add to currentIndex
but then get the following error;
二元运算符'+ ='不能应用于两个NSNumber操作数
Binary operator '+=' cannot be applied to two NSNumber operands
&&我得到的第二个错误是
&& the second error I get is
没有'+'候选人产生预期的上下文结果类型NSNumber
No '+' candidates produce the expected contextual result type NSNumber
let num: Int = 210
let num2: Int = item.points.intValue
item.points = num + num2
这里我只是尝试将210添加到points属性值 item
是一个 NSManagedObject
。
Here I am just trying to add 210 to the points property value, item
is a NSManagedObject
.
所以基本上我在向 NSNumber
类型的属性添加数字时遇到了问题。我正在使用 NSNumber
,因为它们是 NSManagedObject
的属性。
So basically I am having issues getting my head around adding numbers to properties of type NSNumber
. I am working with NSNumber
because they are properties of NSManagedObject
's.
任何人都可以帮助我吗?我有80多个错误,这些错误都是上面提到的错误之一。
Can anyone help me out ? I have over 80 errors which are all either one of the above errors mentioned.
谢谢
推荐答案
在Swift 3之前,很多类型都是自动在必要时桥接到某个 NSObject
子类的
实例,例如 String
到
NSString
,或 Int
, Float
,...到 NSNumber
。
Before Swift 3, many types were automatically "bridged" to an
instance of some NSObject
subclass where necessary, such as String
to
NSString
, or Int
, Float
, ... to NSNumber
.
从Swift 3开始,您必须明确转换:
As of Swift 3 you have to make that conversion explicit:
var currentIndex = 0
for item in self.selectedFolder.arrayOfTasks {
item.index = currentIndex as NSNumber // <--
currentIndex += 1
}
或者,使用选项使用标量原始数据类型的属性在创建 NSManagedObject
子类时,
然后该属性有一些整数类型而不是 NSNumber
,
这样你就可以在不转换的情况下获得并设置它。
Alternatively, use the option "Use scalar properties for primitive data types" when creating the NSManagedObject
subclass,
then the property has some integer type instead of NSNumber
,
so that you can get and set it without conversion.
这篇关于使用NSNumber& Swift 3中的整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!