The remove()
method removes an element from the array at the specified index.
Example
// create an array
var prime = [2, 3, 5, 7, 9, 11]
// remove 9 from the array
prime.remove(at:4)
// print updated prime array
print(prime)
// Output: [2,3,5,7,11]
remove() Syntax
The syntax of the array remove()
method is:
array.remove(at: index)
Here, array is an object of the Array
class.
remove() Parameters
The remove()
method takes only one parameter:
- index - index of the element to remove
remove() Return Value
- returns the element that was removed from array
Example: Swift Array remove()
// languages array
var languages = ["Swift", "C", "Objective-C"]
print("Before Removing:", languages)
// "Objective-C" (at index 2) is removed
var removed = languages.remove(at: 2)
print("After Removing:", languages)
print("Removed Element:", removed)
Output
Before Removing: ["Swift", "C", "Objective-C"] After Removing: ["Swift", "C"] Removed Element: Objective-C
Here, we have removed "Objective-C"
from the languages array. The removed element is stored in the removed variable.