drop(where: {}) remove(where: {}) function in Swift?
Here is an extension that returns an array of dropped elements:
extension Array {
mutating func dropWhere(_ isIncluded: (Element) throws -> Bool) -> [Element] {
do {
let reverseArray = try filter { try isIncluded($0) }
self = try filter { try !isIncluded($0) }
return reverseArray
} catch {
return []
}
}
}
Just call it like you would call filter
.
var array = [1, 2, 3]
let array2 = array.dropWhere { $0 > 2 }
print(array) //[1, 2]
print(array2) //[3]
Code I've finished with:
extension Array {
mutating func popFirstElementWith(_ predicate:(Element)->(Bool)) -> Element? {
for (idx, element) in enumerated() {
if predicate(element) {
remove(at: idx)
return element
}
}
return nil
}
}
Swift 5 has removeAll(where)
@inlinable public mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
You can use it like that -
[1,2,3].removeAll(where: { $0 == 2})
Apple Docs