How to remove an element from an array in Swift

后端 未结 18 2007
灰色年华
灰色年华 2020-11-28 18:38

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\", \"m         


        
18条回答
  •  有刺的猬
    2020-11-28 18:45

    Given

    var animals = ["cats", "dogs", "chimps", "moose"]
    

    Remove first element

    animals.removeFirst() // "cats"
    print(animals)        // ["dogs", "chimps", "moose"]
    

    Remove last element

    animals.removeLast() // "moose"
    print(animals)       // ["cats", "dogs", "chimps"]
    

    Remove element at index

    animals.remove(at: 2) // "chimps"
    print(animals)           // ["cats", "dogs", "moose"]
    

    Remove element of unknown index

    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"]
    

    Notes

    • The above methods modify the array in place (except for filter) and return the element that was removed.
    • Swift Guide to Map Filter Reduce
    • If you don't want to modify the original array, you can use dropFirst or dropLast to create a new array.

    Updated to Swift 5.2

提交回复
热议问题