iosiphonearraysswiftelement

Remove Specific Array Element, Equal to String - Swift


Is there no easy way to remove a specific element from an array, if it is equal to a given string? The workarounds are to find the index of the element of the array you wish to remove, and then removeAtIndex, or to create a new array where you append all elements that are not equal to the given string. But is there no quicker way?


Solution

  • You can use filter() to filter your array as follow

    var strings = ["Hello","Playground","World"]
    
    strings = strings.filter { $0 != "Hello" }
    
    print(strings)   // "["Playground", "World"]\n"
    

    edit/update:

    Xcode 10 • Swift 4.2 or later

    You can use the new RangeReplaceableCollection mutating method called removeAll(where:)

    var strings = ["Hello","Playground","World"]
    
    strings.removeAll { $0 == "Hello" }
    
    print(strings)   // "["Playground", "World"]\n"
    

    If you need to remove only the first occurrence of an element we can implement a custom remove method on RangeReplaceableCollection constraining the elements to Equatable:

    extension RangeReplaceableCollection where Element: Equatable {
        @discardableResult
        mutating func removeFirst(_ element: Element) -> Element? {
            guard let index = firstIndex(of: element) else { return nil }
            return remove(at: index)
        }
    }
    

    Or using a predicate for non Equatable elements:

    extension RangeReplaceableCollection {
        @discardableResult
        mutating func removeFirst(where predicate: @escaping (Element) throws -> Bool) rethrows -> Element? {
            guard let index = try firstIndex(where: predicate) else { return nil }
            return remove(at: index)
        }
    }
    

    var strings = ["Hello","Playground","World"]
    strings.removeFirst("Hello")
    print(strings)   // "["Playground", "World"]\n"
    strings.removeFirst { $0 == "Playground" }
    print(strings)   // "["World"]\n"