Subscript Syntax to append values in array

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!


Source: syntax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.