Swift Array prefix()

The prefix() method returns the specified number of elements from the starting element.

Example

var numbers = [2, 4, 6, 8, 10, 11, 12, 13]

// return first 5 elements print(numbers.prefix(5))
// Output: [ 2, 4, 6, 8, 10 ]

prefix() Syntax

The syntax of the array prefix() method is:

array.prefix(number: Int)

Here, array is an object of the Array class.


prefix() Parameters

The prefix() method takes a single parameter:

  • number - number of elements to return from array

Note: number must be greater than or equal to 0.


prefix() Return Value

  • returns the specified number of elements from the starting element.

Example 1: Swift Array prefix()

var languages = ["Swift", "C", "Java", "Objective-C", "Kotlin"]

// return first 3 elements print(languages.prefix(3))
var prime = [9, 12, 52, 43]
// return first 2 elements print(prime.prefix(2))

Output

["Swift", "C", "Java"]
[9, 12]

In the above example,

  • languages.prefix(3) returns the first 3 elements of the languages array
  • prime.prefix(2) returns the first 2 elements of the prime array.

Example 2: Return Empty And Original Array using prefix()

var names = ["Greg", "Ludovico", "Ben", "Cartman"]

// return empty array print(names.prefix(0))
// return original array print(names.prefix(4))

Output

[]
["Greg", "Ludovico", "Ben", "Cartman"]

Here,

  • names.prefix(0) - since we have passed 0, the method returns an empty array.
  • names.prefix(4) - since the number of elements to return (4) is equal to the number of elements in the array, the method returns the original array.

Note: Even if the number of elements to return is greater than the number of elements in the array, the method returns the original array.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges