Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save JadenGeller/9b6028eded1f3ea45b6c to your computer and use it in GitHub Desktop.

Select an option

Save JadenGeller/9b6028eded1f3ea45b6c to your computer and use it in GitHub Desktop.
Swift Array Remove Matching
extension Array {
/*
* Similiar to filter, but removes the results that match
* in addition to returning them
*/
mutating func removeMatching(removeElement: T -> Bool) -> [T] {
var removed = [T]()
for index in stride(from: self.endIndex-1, through: 0, by: -1) {
let element = self[index]
if removeElement(element) {
removeAtIndex(index)
removed.append(element)
}
}
return removed
}
}
var all = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let odd = all.removeMatching({ x in x % 2 != 0 })
// all == [2, 4, 6, 8, 10]
// odd == [1, 3, 5, 7, 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment