How To Return First Or Last Objects Of An Array In Swift

Here’s a quick way to get the first couple or last couple of elements in an array.

How To Return First Objects Of An Array In Swift

Use the prefix function.

let array = [1, 2, 3, 4, 5]
let firstThree = array.prefix(3)
print(firstThree)

This prints [1, 2, 3]

How To Return Last Objects Of An Array In Swift

Use the suffix function.

let array = [1, 2, 3, 4, 5]
let lastThree = array.suffix(3)
print(lastThree)

This prints [3, 4, 5]

What About Out Of Bounds Errors?

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]

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts