manatee manatee - 5 months ago 26
Swift Question

Why is the Int immutable?

I have an NSDictionary, and there is an array within it composed of integers, and I am trying to change an integer at a certain index. I am getting this error though

Cannot assign to immutable expression of type Int


var avafdg = object["Availability"] as? NSDictionary //I am importing the Dictionary from Parse, and it is imported correctly.
avafdg![0]![12] as! Int = 1 // I get the error here

Answer

You cannot assign to a result of operator as!. Subscript [] operator of a Dictionary is tricky in that when you write

avafdg![123] = 456

Swift knows to call an update method to process this assignment. However, once you do a cast, the assignment is no longer possible. In fact, it no longer makes sense, for the same reason as an assignment to the result of, say, an addition operation, would be meaningless:

x+5 = 6 // <<== Will not compile

Fortunately, you do not need to cast to an Int in order to store a new Int into your dictionary. You need to tell Swift that whatever is returned by the first indirection is a NSMutableDictionary*, too:

var innerDictionary = avafdg![0] as NSMutableDictionary!
innerDictionary[12] = 1

* I am assuming that it is NSMutableDictionary, but it could be NSMutableArray as well, depending on the data structure that you have.

Comments