The prefix() method returns the specified number of elements from the starting element.
Example
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()
Output
["Swift", "C", "Java"] [9, 12]
In the above example,
languages.prefix(3)returns the first 3 elements of the languages arrayprime.prefix(2)returns the first 2 elements of the prime array.
Example 2: Return Empty And Original Array using prefix()
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.