How can I unset/remove an element from an array in Apple's new language Swift?
Here's some code:
let animals = ["cats", "dogs", "chimps", "moose"]
How could the element animals[2] be removed from the array?
To remove an element from the Swift Array, use array. remove(at:index) method. Remember that the index of an array starts at 0. If you want to remove ith element use the index as (i-1).
To remove first element from Array in Swift, call remove(at:) method on this array and pass the index 0 for at parameter. Or call removeFirst() method on the array.
We can remove all elements of an array that satisfy a given predicate in Swift by using the removeAll(where:) method.
The let keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var instead, e.g:
var animals = ["cats", "dogs", "chimps", "moose"]
animals.remove(at: 2)  //["cats", "dogs", "moose"]
A non-mutating alternative that will keep the original collection unchanged is to use filter to create a new collection without the elements you want removed, e.g:
let pets = animals.filter { $0 != "chimps" }
                        Given
var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeFirst() // "cats"
print(animals)        // ["dogs", "chimps", "moose"]
animals.removeLast() // "moose"
print(animals)       // ["cats", "dogs", "chimps"]
animals.remove(at: 2) // "chimps"
print(animals)           // ["cats", "dogs", "moose"]
For only one element
if let index = animals.firstIndex(of: "chimps") {
    animals.remove(at: index)
}
print(animals) // ["cats", "dogs", "moose"]
For multiple elements
var animals = ["cats", "dogs", "chimps", "moose", "chimps"]
animals = animals.filter(){$0 != "chimps"}
print(animals) // ["cats", "dogs", "moose"]
filter) and return the element that was removed.dropFirst or dropLast to create a new array.Updated to Swift 5.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With