Max_Rai Max_Rai - 8 months ago 24
Swift Question

casting mutable array is still considered non-mutable in swift

I tried casting AnyObject data to mutable array but it still worked like a non-mutable array and crashes on run-time after trying to mutate it. Can someone explain please?

Like I am getting some data from JSON and I know it is going to be of Array data type (I am naming it data), now I cast it to mutable array, suppose like this:

let mutArray: NSMutableArray = data as! NSMutableArray

but mutArray still remains as a non-mutable array when I later try to mutate it. This code worked perfect few months back and now it is giving issues like I am trying to mutate a non-mutable array.


That's because casting doesn't actually change an object in any way, it just tells the compiler it's of a certain type. In other words, it only affects the way the code is type-checked, it doesn't actually change the behavior of the code at runtime. To actually change an NSArray into an NSMutableArray you'd need to:

let mutArray = NSMutableArray(array: data)

This line actually creates a new NSMutableArray and populates it with your data array.

If your code worked before, then for some reason, your original data must have already been an NSMutableArray. It's actually pretty common for NSArrays to secretly be NSMutableArrays (though it is of course a bad idea to rely on that fact from any given method, since as we just learned, it could change at any moment).