How to return first 5 objects of Array in Swift?
By far the neatest way to get the first N elements of a Swift array is using prefix(_ maxLength: Int)
:
let array = [1, 2, 3, 4, 5, 6, 7]
let slice5 = array.prefix(5) // ArraySlice
let array5 = Array(slice5) // [1, 2, 3, 4, 5]
the one-liner is:
let first5 = Array(array.prefix(5))
This has the benefit of being bounds safe. If the count you pass to prefix
is larger than the array count then it just returns the whole array.
NOTE: as pointed out in the comments, Array.prefix
actually returns an ArraySlice
, not an Array
.
If you need to assign the result to an Array
type or pass it to a method that's expecting an Array
param, you will need to force the result into an Array
type: let first5 = Array(array.prefix(5))
You can do it really easy without filter
, map
, reduce
, or prefix
by just returning a range of your array via a subscript:
var wholeArray = [1, 2, 3, 4, 5, 6]
var n = 5
var firstFiveSlice = wholeArray[0..<n] // 1,2,3,4,5
let firstFiveArray = Array(firstFiveSlice)