Theilya Theilya - 5 months ago 132
Swift Question

swift :changing the content of an array gives me an error

I have this array :

var array = [[12,46,["a","b","c"],"nil",true,7,true],[10,40,["c","d","e"],"nil",true,7,true],[0,1,["z","l","w"],"hey",false,7,true]].


when I try to change the value of the last boolean of an array boolean by this code :

array[0][6] = false


I get this error "cannot assign through subscript subscript is get-only array"

Answer

Interesting. I think the compiler tripped up somewhere. You only have to examine the array's type to understand why:

var array = [
    [12,46,["a","b","c"],"nil",true,7,true],
    [10,40,["c","d","e"],"nil",true,7,true],
    [0,1,["z","l","w"],"hey",false,7,true]
]

print(array.dynamicType) // Array<NSArray>
                         // can't assign to the inner array since NSArray is immutable

Give Swift a hint of the inner type and it works

var array: [[AnyObject]] = [
    [12,46,["a","b","c"],"nil",true,7,true],
    [10,40,["c","d","e"],"nil",true,7,true],
    [0,1,["z","l","w"],"hey",false,7,true]
]

array[0][6] = false     // works