Skip to content

Instantly share code, notes, and snippets.

@steverichey
Created April 21, 2016 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steverichey/c52c9c52b9218fb3aed9b5089920809d to your computer and use it in GitHub Desktop.
Save steverichey/c52c9c52b9218fb3aed9b5089920809d to your computer and use it in GitHub Desktop.
A Swift extension to perform two filters simultaneously.
extension SequenceType {
/**
Filter a single sequence into two "buckets", each an array containing objects of this collection's element type.
- parameter includeElementInFirstCollection: A method that returns true for elements to include in the first collection.
- parameter includeElementInSecondCollection: A method that returns true for elements to include in the second collection.
- returns: A tuple of two arrays containing the elements in their respective buckets.
*/
@warn_unused_result
public func multifilter(@noescape includeInFirst includeElementInFirstCollection: (Self.Generator.Element) throws -> Bool, @noescape includeInSecond includeElementInSecondCollection: (Self.Generator.Element) throws -> Bool) rethrows -> ([Self.Generator.Element], [Self.Generator.Element]) {
var firstCollection: [Self.Generator.Element] = []
var secondCollection: [Self.Generator.Element] = []
for element in self {
if try includeElementInFirstCollection(element) {
firstCollection.append(element)
}
if try includeElementInSecondCollection(element) {
secondCollection.append(element)
}
}
return (first: firstCollection, second: secondCollection)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment