Last time, we saw how to change existing items in an array using their index, like colors[1] = "yellow"
.
But what if you want to add a new item to the array without replacing an existing one.
Engagement Message
How might you add to the collection?
Swift arrays have a special built-in method just for this: .append()
.
This method adds the specified item to the very end of the array. The array grows by one item.
Engagement Message
With me so far?
Here's how you use it: arrayName.append(newItem)
.
If we have var tasks = ["review code"]
, and we run tasks.append("write tests")
, the array changes.
Engagement Message
How long do you think the array will be after this operation?
After running the operation the tasks
array becomes ["review code", "write tests"]
. The new item "write tests"
is added at the end.
You can append items of any data type (strings, numbers, booleans) to an array, as long as they match the array's type.
Engagement Message
Do you think you can append an array to an array?
