How to remove an element from an array in Swift

后端 未结 18 2150
灰色年华
灰色年华 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:57

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

提交回复
热议问题