What is the remove() method of an array in Swift?
Overview
An array’s elements can be removed in Swift using the remove() method.
We only have to pass the element’s index to delete the elements.
Syntax
arr.remove(at: index)
Syntax to remove an element in an array in Swift
Return type
It’s return type is void.
Parameters
index: This refers to the index position of the array to remove. In this case, the array is arr.
Code example
// create an arrayvar vowels = ["a", "e", "p", "i", "o", "u", "k"]// print initial arrayprint(vowels)// remove elementvowels.remove(at : 2) // remove "p"//print new arrayprint(vowels)// remove elementvowels.remove(at : 5) // remove "k"// print arrayfor letter in vowels{print(letter)}
Explanation
- Line 2: We create an array named
vowels. - Line 4: We print the array’s values to the console.
- Line 6: An element at index 2 is removed. This is the character
"p". After this, the array has six remaining elements. - Line 8: The array will not remain the same since an element has been removed. So, we print the modified array on this line.
- Line 10: An element at index 5 is removed from the modified array.
- Line 12: We print the elements of the modified array using the
for-inloop.