Search code examples
arraysswift

How to remove an element from an array in Swift


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?


Solution

  • 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" }