I don't have any problem, i would just like some clarification on an issue regarding mutability.
In Objective-C we would use for example NSMutableArray
to get a mutable array and an NSArray
to get an immutable one. I don't know much about the inner workings of the two, but from what I can remember I believe that the difference is that NSArray
only reserves an amount of memory specific to the initial value which makes it more efficient, while NSMutableArray
has no idea how much memory it will require. Presumably this means that NSMutableArray
has pointers to bits of memory that are all over the place and not one by one like with NSArray
? Or does it perhaps just reserve a lot of memory hoping it won't run out?
In Swift the obvious substitution is let
for immutable and var
for mutable. If a variable is declared with these keywords that I see no difference between Swift and Objective-C. However, I don't understand how it works if I declare the variable without the var/let by, for example, storing it in another variable.
Let's say I have a dictionary such as [String: [String]]
. In other words, for each string key there is an array of strings. Consider the following case:
var dictionary: [String: [String]] = [:]
dictionary["key"] = ["string0", "string1"]
//dictionary now is ["key": ["string0", "string1"]]
But what is the strings array now? Is it mutable because the dictionary is mutable? Is it mutable because everything we assign is mutable? How about the following case:
let dictionary = ["key": ["string0", "string1"]]
dictionary["key"].append("string2")
Would this work?
I guess the key issue is that in Objective-C I always define whether am I working with NSMutableArray
or NSArray
. Creating an array using the literal syntax [@"string"]
always leads to an NSArray
and it won't be mutable unless I specify it. In Swift I don't know when is what mutable.
Thanks