Here’s a quick way to get the first couple or last couple of elements in an array.
Use the prefix function.
let array = [1, 2, 3, 4, 5]
let firstThree = array.prefix(3)
print(firstThree)This prints [1, 2, 3]
Use the suffix function.
let array = [1, 2, 3, 4, 5]
let lastThree = array.suffix(3)
print(lastThree)This prints [3, 4, 5]
Both prefix and suffix are safe from out of bounds errors.
For example:
let array = [1, 2, 3, 4, 5]
let lastTen = array.suffix(10)
print(lastTen)This doesn’t crash and simply prints [1, 2, 3, 4, 5]

The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.