Last active
August 29, 2015 14:16
-
-
Save JadenGeller/9b6028eded1f3ea45b6c to your computer and use it in GitHub Desktop.
Swift Array Remove Matching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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