Swift arrays use value (copy) semantics but in fact they are passed and assigned as references. Only when a change of the array size or an reordering of the elements occurs the array is really copied. This is called "lazy copy" or "copy on write". You do not have to be scared to simply assign an array like this:
var temp = someBigArray
It is not copied. But when you call:
temp.append(someValue)
Then an actual copy happens.
In your code in this line:
if var table = self.database[tableName]
The array is not copied.
In this line:
table.append(theRecord)
It is copied.
In this line:
self.database[tableName] = table
It is not copied but the ref-count of the array in the dictionary is decremented by one and if no other reference to this array exists it is deallocated. The "table" array is then just passed as a reference into "self.database[tableName]". No copy occurs here.
But Eric D's answer is correct, by calling append() directly on the array (with the ? operator) the least overhead is created. This is how you should do it:
self.database[tableName]?.append(theRecord)
But it can happen also in append() that the array get's copied - which is the case if the array size has to be extended and there is no pre-allocated space. This is because arrays always has to have contiguous memory.
So by calling append() it can happen that the array has to do this:
- allocate a new contiguous memory block with the current count size plus at least one entry more. (usually it allocates even more then that, just in case you will append more in the future)
- copy the whole content into the new memory block (including the new entry)
- release the "old" memory (this is in fact more complicated because other arrays could reference the old memory, in this case it's not released)
So usually you do not have to care about "inefficient" copy of arrays - the compiler knows better.