Swift Language Arrays Removing element from an array without knowing it's index


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:


extension Array where Element: Equatable {

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


    var array = ["abc", "lmn", "pqr", "stu", "xyz"]
    print("\(array)")    //["abc", "pqr", "stu", "xyz"]
    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