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

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts