In the Swift Programming Language book it explicitly states:
You can't use subscript syntax to append a new item to the end of an array
The example provided in the book also states that even if the replacement set of values has a different length than the range you are replacing it is fine. So for example:
var shoppingList = ["Eggs", "Milk", "Chocolate"]
shoppingList[0...2] = ["Bananas", "Apples"]
// shoppingList = ["Bananas", "Apples"]
which makes sense because you are replacing 3 values with the values of Banana and Apple. However, if we did this instead:
var shoppingList = ["Eggs", "Milk", "Chocolate"]
shoppingList[0...2] = ["Bananas", "Apples", "Sausage", "Pear"]
// shoppingList = ["Bananas", "Apples", "Sausage", "Pear"]
I thought we were not allowed to use subscript syntax to append a new item to the end of the array, but this seems like a loophole in the language. Can someone explain to me why this happens and/if this is a valid behaviour or is a bug? Thanks!
A subscript is nothing else than a function without a name. It can do anything a function can -> modifying is is possible. As with every function though, if you're passing invalid parameters it will fail.
When using a subscript with an array like array[index]
to set a new value, the array simple replaces the existing value with the input, so if you entered an index which doesn't exist yet, it cannot replace the value and will therefore fail.
The book was referring to something like
var array = [0, 1, 2]
array[3] = 3
which would give you an indexOutOfBounds
error, because the index 3 doesn't exist yet and the subscript doesn't automatically add a new element.
Let's assume the implementation of this subscript would check to see if the index doesn't exist yet and adds it when needed. What could happen:
var array = [0, 1, 2]
array[100] = 3 // Index 100 doesn't exist -> But what to add at index 3 to 99?
Also every time you'd assign something to an array a check would have to be made which would be incredibly slow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With