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))