How to remove an element from an array in Swift

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

    You could do that. First make sure Dog really exists in the array, then remove it. Add the for statement if you believe Dog may happens more than once on your array.

    var animals = ["Dog", "Cat", "Mouse", "Dog"]
    let animalToRemove = "Dog"
    
    for object in animals {
        if object == animalToRemove {
            animals.remove(at: animals.firstIndex(of: animalToRemove)!)
        }
    }
    

    If you are sure Dog exits in the array and happened only once just do that:

    animals.remove(at: animals.firstIndex(of: animalToRemove)!)
    

    If you have both, strings and numbers

    var array = [12, 23, "Dog", 78, 23]
    let numberToRemove = 23
    let animalToRemove = "Dog"
    
    for object in array {
    
        if object is Int {
            // this will deal with integer. You can change to Float, Bool, etc...
            if object == numberToRemove {
            array.remove(at: array.firstIndex(of: numberToRemove)!)
            }
        }
        if object is String {
            // this will deal with strings
            if object == animalToRemove {
            array.remove(at: array.firstIndex(of: animalToRemove)!)
            }
        }
    }
    

提交回复
热议问题