Fix: Getting the First N Elements of an Array in Swift

Written by

in

Quick answer: Use array.prefix(n) to get up to the first n elements without going past the end of the array. The result is an ArraySlice; wrap it in Array(...) if you need an Array.

Why this happens

To take the first five elements of an array, you might reach for a loop or use a range such as items[0..<5]. A range subscript works only when those indices are valid. If the array contains fewer than five elements, the subscript traps at runtime.

Swift provides prefix(_:) for this task. It returns up to the requested number of elements, so a short array is safe. For an array, the result is an ArraySlice, which matters when a function or property expects an Array instead.

How to fix it

1. Use prefix(_:) and convert the result to an array

Call prefix(_:) with the maximum number of elements you want. Wrap the result in Array(...) when the result needs to be an array:

let numbers = [1, 2, 3, 4, 5, 6, 7]
let firstFive = Array(numbers.prefix(5))

print(firstFive) // [1, 2, 3, 4, 5]

This preserves the original order and does not modify numbers. You do not need filter, map, or reduce just to select the first elements.

The requested count is a maximum, not a requirement. If the array has fewer elements, prefix(_:) returns all of them:

let numbers = [1, 2, 3]
let firstFive = Array(numbers.prefix(5))

print(firstFive) // [1, 2, 3]

An empty array produces an empty result, and requesting zero elements does the same. The count passed to prefix(_:) must be nonnegative. If it comes from a caller or user input, validate it before calling the method.

For example, this helper treats a negative request as zero:

func firstElements(_ numbers: [Int], count: Int) -> [Int] {
    Array(numbers.prefix(max(0, count)))
}

let result = firstElements([10, 20, 30], count: 2)
print(result) // [10, 20]

If a negative count represents a programming error in your app, reject it instead of silently replacing it with zero. The right behavior depends on what the count means in your code.

2. Keep the slice when an array is not required

You can omit the conversion if you only need to read or iterate over the selected elements:

let names = ["Ava", "Bo", "Chen", "Dara", "Emil", "Finn"]
let firstNames = names.prefix(5) // ArraySlice<String>

for name in firstNames {
    print(name)
}

A slice supports common collection operations, including iteration and checking whether it is empty. Keeping it as a slice is useful when the next operation can work with that type. If an API specifically takes [String], convert at the point where you call it:

func showNames(_ names: [String]) {
    for name in names {
        print(name)
    }
}

let names = ["Ava", "Bo", "Chen", "Dara", "Emil", "Finn"]
let firstNames = names.prefix(5)
showNames(Array(firstNames))

Be careful with indices when working with slices in general. An ArraySlice preserves the indices of the collection it came from; an arbitrary slice does not necessarily start at zero. Use first, iterate over the slice, or use its own startIndex rather than assuming slice[0] exists.

let values = [10, 20, 30, 40]
let middle = values[1..<3]

print(middle.first as Any) // Optional(20)
print(middle[middle.startIndex]) // 20

The startIndex subscript in this example is safe because middle is known to be nonempty. For a slice that might be empty, first is the safer choice because it returns an optional.

Slices can also retain the storage of a larger array. If you plan to keep a small result around for a long time, convert it to an Array rather than keeping a slice of the large collection.

3. Use a range subscript only when you control the bounds

A range subscript is an alternative when you know the array contains enough elements:

let numbers = [1, 2, 3, 4, 5, 6]
let firstFive = Array(numbers[0..<5])

print(firstFive) // [1, 2, 3, 4, 5]

Like prefix(_:), the range subscript produces an ArraySlice, so the example converts it to an array. Unlike prefix(_:), this range is not automatically shortened if the array contains fewer than five elements. Using the same subscript on [1, 2, 3] traps because the upper bound is invalid.

If you must construct a range from a variable count, clamp both ends of the requested size before subscripting:

let numbers = [1, 2, 3]
let requestedCount = 5
let safeCount = min(max(requestedCount, 0), numbers.count)
let selected = Array(numbers[0..<safeCount])

print(selected) // [1, 2, 3]

For the first N elements, prefix(_:) is usually clearer because it handles a request larger than the array for you. The explicit range can still be useful when range-based code is already part of the surrounding logic.

How to prevent it

  • Prefer prefix(_:) over a fixed range when the array length can vary.
  • Validate counts before passing them to prefix(_:); negative counts are invalid.
  • Convert the slice with Array(...) when the receiving API requires an array or when you need a standalone result.
  • Test with an empty array, an array shorter than the requested count, and a count of zero.
  • Avoid assuming that an arbitrary ArraySlice starts at index zero.

FAQ

Does prefix(5) fail if the array has fewer than five elements?

No. It returns the available elements, up to a maximum of five. An empty array produces an empty slice.

Why can’t I pass the result of prefix(_:) to a function expecting an array?

For an array, prefix(_:) returns an ArraySlice, not an Array. Convert it with Array(items.prefix(5)) before passing it to a function that requires an array.

Should I use filter, map, or reduce to get the first elements?

Use prefix(_:) for selecting by position. Use filter when selection depends on a condition, map when you need to transform elements, and reduce when combining them into a result.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.