Reputation: 831
I have a variable populated from a keystore, that when incremented, gives an error that reads: "NSNumber is not convertible to @lvalue UIint8"
if let bankbalance: AnyObject? = keystore.objectForKey("coinbalance"){
let mybalance = bankbalance as NSNumber
mybalance += 50 //this line gives the error
}
My question is what is convertible to UIint8 so that I can add to my variable? I've tried INT, Float, double.
Upvotes: 2
Views: 3760
Reputation: 3181
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;
}
Upvotes: 5
Reputation: 37189
You cannot increment constants.let
is keyword in swift for constants which means after defining its value you cannot alter it.
var
is another keyword which means variable and you can alter the value which declared with var keyword.
if let bankbalance: AnyObject? = keystore.objectForKey("coinbalance"){
//use var instead of let
var mybalance = bankbalance as NSNumber
mybalance = mybalance.integerValue + 50 //use integervalue as we cast to `NSNumber`
}
this will works
Upvotes: 3
Reputation: 4551
You are trying to add a value to a let
and let is a constant, you can not assign values to a let
after you initialized it.
Apple docs:
Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type (such as the number 10 or the string "Hello"). The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future.
var
is what you want
Upvotes: 8