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.
arr.prefix(maxLength)
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.
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
.
// 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"]
prefix(_:)
method, along with some arguments. Then, we print the results to the console.RELATED TAGS
CONTRIBUTOR
View all Courses