Removing element from an array without knowing its index

suggest change

remove(at:) needs an index. This extension removes the first element equal to a value when the index is not known. Swift 5 names the lookup firstIndex(of:); Swift 3 and 4 use index(of:).

Swift3

extension Array where Element: Equatable {

    mutating func remove(_ element: Element) {
        _ = index(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

e.g.

var array = ["abc", "lmn", "pqr", "stu", "xyz"]
array.remove("lmn")
print("\(array)")    //["abc", "pqr", "stu", "xyz"]

array.remove("nonexistent")
print("\(array)")    //["abc", "pqr", "stu", "xyz"]
//if provided element value is not present, then it will do nothing!

A value of a different type, such as array.remove(25) on [String], is a compile-time error:

cannot convert value to expected argument type

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents