Remove Specific Array Element, Equal to String - Swift

前端 未结 8 1952
臣服心动
臣服心动 2020-12-23 16:07

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

8条回答
  •  无人及你
    2020-12-23 16:51

    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"
    

提交回复
热议问题