Removing element from an array without knowing its index
suggest changeremove(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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents