Last time, we learned how to add items to the end of an array using .append()
, which lets our arrays grow.
But what if we need to take an item out of an array? For example, removing the first or last task from a to-do list.
Engagement Message
When might you want to remove the first item from a list instead of the last?
Swift arrays have a simple method for removing the item from the very end of the array: the .removeLast()
method.
This is the perfect opposite of .append()
. The array gets shorter by one item.
Engagement Message
Does .removeLast()
seem like a useful tool for an "undo" feature?
Similarly, Swift provides the .removeFirst()
method to remove the item from the very beginning of an array.
If we have:
and run:
the array becomes ["Second", "Third"]
.
Engagement Message
If you were managing a queue of people, which method would you use to process the next person in line?
The syntax for both is simple. They don't need any arguments inside the parentheses because they always know which item to remove.
