0Pricing
Swift Academy · Lesson

prefix, suffix, and dropFirst

Take portions of a collection declaratively.

prefix(n)

prefix(n) returns a slice of the first n elements. It is safe even if n is larger than the array.

let arr = [1, 2, 3, 4, 5]
print(Array(arr.prefix(3)))
print(Array(arr.prefix(99)))

suffix(n)

suffix(n) returns a slice of the last n elements, also clamped safely.

let arr = [1, 2, 3, 4, 5]
print(Array(arr.suffix(2)))
print(Array(arr.suffix(0)))

All lessons in this course

  1. Creating Slices with Ranges
  2. ArraySlice Index Semantics
  3. Converting Slices Back to Arrays
  4. prefix, suffix, and dropFirst
← Back to Swift Academy