Remove Specific Array Element, Equal to String – Swift

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

Leave a Comment