Removing element from an array without knowing its index

suggest change

Generally, if we want to remove an element from an array, we need to know it’s index so that we can remove it easily using remove(at:) function.

But what if we don’t know the index but we know the value of element to be removed!

So here is the simple extension to an array which will allow us to remove an element from array easily without knowing it’s index:

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!

Also if, by mistake, we did something like this: array.remove(25) i.e. we provided value with different data type, compiler will throw an error mentioning-

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