How to remove an element from an array in Swift

后端 未结 18 2009
灰色年华
灰色年华 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" }
    
    0 讨论(0)
  • 2020-11-28 18:58

    Regarding @Suragch's Alternative to "Remove element of unknown index":

    There is a more powerful version of "indexOf(element)" that will match on a predicate instead of the object itself. It goes by the same name but it called by myObjects.indexOf{$0.property = valueToMatch}. It returns the index of the first matching item found in myObjects array.

    If the element is an object/struct, you may want to remove that element based on a value of one of its properties. Eg, you have a Car class having car.color property, and you want to remove the "red" car from your carsArray.

    if let validIndex = (carsArray.indexOf{$0.color == UIColor.redColor()}) {
      carsArray.removeAtIndex(validIndex)
    }
    

    Foreseeably, you could rework this to remove "all" red cars by embedding the above if statement within a repeat/while loop, and attaching an else block to set a flag to "break" out of the loop.

    0 讨论(0)
  • 2020-11-28 18:59

    Swift 5: Here is a cool and easy extension to remove elements in an array, without filtering :

       extension Array where Element: Equatable {
    
        // Remove first collection element that is equal to the given `object`:
        mutating func remove(object: Element) {
            guard let index = firstIndex(of: object) else {return}
            remove(at: index)
        }
    
    }
    

    Usage :

    var myArray = ["cat", "barbecue", "pancake", "frog"]
    let objectToRemove = "cat"
    
    myArray.remove(object: objectToRemove) // ["barbecue", "pancake", "frog"]
    

    Also works with other types, such as Int since Element is a generic type:

    var myArray = [4, 8, 17, 6, 2]
    let objectToRemove = 17
    
    myArray.remove(object: objectToRemove) // [4, 8, 6, 2]
    
    0 讨论(0)
  • 2020-11-28 19:00

    For Swift4:

    list = list.filter{$0 != "your Value"}
    
    0 讨论(0)
  • 2020-11-28 19:02

    extension to remove String object

    extension Array {
        mutating func delete(element: String) {
            self = self.filter() { $0 as! String != element }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 19:03

    The above answers seem to presume that you know the index of the element that you want to delete.

    Often you know the reference to the object you want to delete in the array. (You iterated through your array and have found it, e.g.) In such cases it might be easier to work directly with the object reference without also having to pass its index everywhere. Hence, I suggest this solution. It uses the identity operator !==, which you use to test whether two object references both refer to the same object instance.

    func delete(element: String) {
        list = list.filter { $0 !== element }
    }
    

    Of course this doesn't just work for Strings.

    0 讨论(0)
提交回复
热议问题