Is it possible to increment a NSNumber variable in iOS swift?
Asked Answered
B

4

5

I used core data in my iOS swift project and declared a variable as Int32, in the class file it was initialised to NSNumber and while I tried to increment the variable by creating a object for that class, it shows that Binary operator += cannot be applied on NSNumber's. Is it possible to increment the NSNumber or should I choose Int16 or Int64 to access the variable.

Bullhead answered 18/8, 2016 at 5:47 Comment(2)
NSNumber objects are immutable. You need to create a new instance with a new value based on the original value.Raji
Bold move by the person who down voted all of the answers.Canaigre
C
12

Here's three different answers from succinct to verbose:

Given that NSNumbers are immutable, simply assign it a new value equal to what you want:

var num : NSNumber = NSNumber(integer: 1) // NSNumber of 1
num = num.integerValue + 1 // NSNumber of 2

Or you can assign it another way:

var num : NSNumber = NSNumber(integer: 1) // NSNumber of 1
num = NSNumber(integer: num.integerValue + 1) // NSNumber of 2

Or you can convert the NSNumber to an Int, increment the int, and reassign the NSNumber:

var num : NSNumber = NSNumber(integer: 1) // NSNumber of 1
var int : Int = Int(num)
int += 1
num = NSNumber(integer: int) // NSNumber of 2
Canaigre answered 18/8, 2016 at 5:51 Comment(1)
All three answers worked correctly.. Thanks a lot for your answers.Bullhead
T
2
var number = NSNumber(integer: 10)
number = number.integerValue + 1
Tarp answered 18/8, 2016 at 5:52 Comment(0)
N
1

Use var. Because let means constants.

var mybalance = bankbalance as NSNumber

But NSNumber is a Object and mybalance.integerValue cannot be assigned.

if let bankbalance: AnyObject? = keystore.objectForKey("coinbalance"){
    let mybalance: NSNumber = bankbalance as NSNumber
    var b = mybalance.integerValue + 50;
}
Nuthouse answered 18/8, 2016 at 5:51 Comment(0)
B
1

It is impossible to increment an NSNumber once the object is created. There is no API that allows that.

You have to recreate the NSNumber object with a new (incremented) value:

let number = NSNumber(int: 15)
let incrementedNumber = NSNumber(int: number.intValue + 1)
Bookrest answered 18/8, 2016 at 5:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.