在Swift 3中使用NSNumber和Integer值

A.R*_*Roe 36 int nsnumber ios swift swift3

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

无法将类型int指定为类型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
 }
Run Code Online (Sandbox Code Playgroud)

甚至当我改变currentIndex一个类型NSNumber然后我得到错误

二进制运算符'+ ='不能应用于'NSNumber'和'Int'类型

所以然后我创建一个名为onetype 的属性NSNumber来添加,currentIndex但后来得到以下错误;

二进制运算符'+ ='不能应用于两个NSNumber操作数

&&我得到的第二个错误是

没有'+'候选者产生预期的上下文结果类型NSNumber

 let num: Int = 210
 let num2: Int = item.points.intValue
 item.points = num + num2
Run Code Online (Sandbox Code Playgroud)

在这里我只想尝试将210添加到points属性值,item是一个NSManagedObject.

所以基本上我遇到了一些问题,我想把数字添加到类型属性中NSNumber.我正在工作,NSNumber因为他们是属性NSManagedObject的.

谁能帮我吗 ?我有80多个错误,这些错误都是上面提到的错误之一.

谢谢

Mar*_*n R 58

斯威夫特3之前,许多类型为自动"桥接"的一些实例NSObject子类在必要时,例如StringNSString,或者Int,Float......到NSNumber.

从Swift 3开始,你必须明确转换:

var currentIndex = 0
for item in self.selectedFolder.arrayOfTasks {
   item.index = currentIndex as NSNumber // <--
   currentIndex += 1
}
Run Code Online (Sandbox Code Playgroud)

或者,在创建NSManagedObject子类时使用"使用标量属性作为基本数据类型"选项,然后该属性具有某种整数类型而不是NSNumber,以便您可以在不进行转换的情况下获取和设置它.

  • 你可以在这里找到完整的解释:[SE-0072](https://github.com/apple/swift-evolution/blob/master/proposals/0072-eliminate-implicit-bridging-conversions.md) (2认同)

dan*_*mbr 6

在Swift 4中(可能与Swift 3中的相同)NSNumber(integer: Int)被替换为NSNumber(value: )where value几乎可以是任何类型的数字:

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


Ham*_*ian 6

斯威夫特 4

var currentIndex:Int = 0
for item in self.selectedFolder.arrayOfTasks {
   item.index = NSNumber(value: currentIndex) // <--
   currentIndex += 1
}
Run Code Online (Sandbox Code Playgroud)