What is the prefix(upTo:) array method in Swift?

Overview

prefix(upTo:) is an array method that is used to return a new array of elements. The new array contains elements of the original array up to, but not including, the specified position.

Syntax

arr.prefix(upTo: position)

Parameters

position: This is the position up to which the returned array returns the elements of arr. The returned elements do not include the element in this position.

Return value

This method returns an array up to, but not including, the specified position.

Code example

// create arrays
let numbers = [2, 1, 45, 3, 9]
let fruits = ["orange", "apple", "banana", "water-melon", "grape"]
let gnaam = ["Google", "Netflix", "Amazon", "Apple", "Meta"]
// get some elements
// and print results
print(numbers.prefix(upTo: 2)) // [2,1]
print(fruits.prefix(upTo: 1)) // ["orange"]
print(gnaam.prefix(upTo: 5)) // ["Google", "Netflix", "Amazon", "Apple", "Meta"]

Explanation

  • Lines 2-4: We create some arrays.
  • Lines 8-10: We invoke the prefix(upTo:) method on the arrays and print the results to the console.

Free Resources