Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

ios - Working with NSNumber & Integer values in Swift 3

I am trying to convert my project to Swift 3.0 however I am having two error messages when working with NSNumber and Integers.

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
 }

and even when I change currentIndex to a type NSNumber then I get the error

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

so then I create a property called one of type NSNumber to add to currentIndex but then get the following error;

Binary operator '+=' cannot be applied to two NSNumber operands

&& the second error I get is

No '+' candidates produce the expected contextual result type NSNumber

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

Here I am just trying to add 210 to the points property value, item is a 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.

Can anyone help me out ? I have over 80 errors which are all either one of the above errors mentioned.

Thanks

question from:https://stackoverflow.com/questions/39321421/working-with-nsnumber-integer-values-in-swift-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...