Last time, we saw how to access array elements using their index, like scores[0]
for the first item. Remember, indices start at 0.
Engagement Message
What if you wanted to get the very last item in an array, especially if you don't know how long the array is?
Swift has a handy solution for this! You can use the .last
property to get the last element directly from any array.
The .last
property always refers to the final item in the array, no matter its length.
Engagement Message
Does this seem like a useful shortcut?
So, if we have:
using planets.last
would give you "Earth"
.
This works no matter how many items are in the array. .last
always gets the final one.
Engagement Message
What would colors.last
give you if colors = ["red", "green", "blue"]
?
Swift also provides a .first
property that works similarly, always giving you the first element of the array.
