Created
April 21, 2016 17:36
-
-
Save steverichey/c52c9c52b9218fb3aed9b5089920809d to your computer and use it in GitHub Desktop.
A Swift extension to perform two filters simultaneously.
This file contains 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 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