Is there a function in the Swift Standard library that acts on a collection, takes a predicate and returns the value removed from that collection?
Currently, I have to implement it in 2 steps:
guard let idx = allAnnotations.index(where: {$0 is MKUserLocation}) else {return}
let userLocation = allAnnotations.remove(at: idx) as! MKUserLocation
But I guess, a similar function exists.
The goal
I have the following array:
[Type1, Type1, Type1, Type1, Type1, Type1, Type2]
Type2
may or may not be present in the array. There are no other types except these two.
I need to split it onto two elements:
[Type1, Type1, Type1, Type1, Type1, Type1]
and
Type2?
That's the function I'm looking for.
Swift 5 has removeAll(where)
@inlinable public mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
You can use it like this -
var array = [1,2,3]
array.removeAll(where: { $0 == 2})
print(array) // [1,3]
Apple Docs
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With