Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
communitycreator

What is array.prefix(_:) in Swift?

Theodore Kelechukwu Onyejiaku

Overview

The array.prefix(_:) method is used to return a new array that contains the number of elements specified by the argument that is passed to it. This means that if we pass 2 as our argument and call this method, the first two elements will be returned in the new array.

Syntax

arr.prefix(maxLength)

Parameters

arr: This is the array that we want to return a new array from.

maxLength: This is the maximum number of elements that can be returned in the new array. It must be greater than or equal to zero.

Return value

The value returned is a new array, starting at the beginning of the original array arr with a number of elements that is equal to or greater than maxLength.

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(2)) // [2,1]
print(fruits.prefix(0))  // []
print(gnaam.prefix(5))   // ["Google", "Netflix", "Amazon", "Apple", "Meta"]
Get the specified number of elements from an array

Code explanation

  • Lines 2–4: We create arrays and initialize them with elements.
  • Lines 8–10: We invoke the prefix(_:) method, along with some arguments. Then, we print the results to the console.

RELATED TAGS

swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring