Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 946
Berny Rayen Avatar asked Aug 18 '16 05:08

Berny Rayen


3 Answers

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
like image 103
Wyetro Avatar answered Oct 12 '22 18:10

Wyetro


var number = NSNumber(integer: 10)
number = number.integerValue + 1
like image 44
Warif Akhand Rishi Avatar answered Oct 12 '22 19:10

Warif Akhand Rishi


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;
}
like image 1
gurmandeep Avatar answered Oct 12 '22 19:10

gurmandeep