在Swift 3中使用NSNumber和Integer值

问题描述 投票:31回答:5

我正在尝试将我的项目转换为Swift 3.0但是在使用NSNumberIntegers时我有两条错误消息。

无法将类型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
 }

甚至当我将currentIndex更改为类型NSNumber然后我得到错误

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

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

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

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

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

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

在这里,我只想尝试将210添加到点属性值,itemNSManagedObject

所以基本上我有问题让我的头脑为NSNumber类型的属性添加数字。我正在与NSNumber合作,因为它们是NSManagedObject的属性。

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

谢谢

ios swift int swift3 nsnumber
5个回答
55
投票

在Swift 3之前,许多类型在必要时自动“桥接”到一些NSObject子类的实例,例如StringNSString,或IntFloat,...到NSNumber

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

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

或者,在创建NSManagedObject子类时使用“使用标量属性用于基本数据类型”选项,然后该属性具有一些整数类型而不是NSNumber,这样您就可以在不进行转换的情况下获取和设置它。


5
投票

在Swift 4中(在Swift 3中它可能是相同的)NSNumber(integer: Int)被替换为NSNumber(value: ),其中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)

3
投票

斯威夫特4:

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

2
投票

您应该保留原始代码并只更改分配,以便它可以工作:

var currentIndex = 0
for item in self.selectedFolder.arrayOfTasks {
    item.index = NSNumber(integer: currentIndex)
    currentIndex += 1
}

由于您的代码在Swift 2中运行良好,我希望这是在下次更新时可能会发生变化的行为。


0
投票

Swift 4.2

item.index = Int(truncating: currentIndex)
© www.soinside.com 2019 - 2024. All rights reserved.