Swift Array – Delete Last N Elements
To delete last N elements of an Array in Swift, call dropLast()
method and pass N
(integer) as argument to dropLast()
method. dropLast()
method returns a new array with N elements dropped from the trailing end of given array.
The syntax to call dropLast()
method on the array is
</>
Copy
var result = arr.dropLast(N)
where N
is an integer, and represents the number of elements we would like to drop from the array at trailing end.
Example
In the following program, we will initialize an array with some values, and delete the last two elements using dropLast()
method.
main.swift
</>
Copy
var arr = [1, 99, 6, 74, 5]
let N = 2
let result = arr.dropLast(N)
print("Original Array: \(arr)")
print("Resulting Array: \(result)")
Output
Conclusion
In this Swift Tutorial, we learned how to get the subsequence which contains the elements of given array, with the last N elements dropped.