Skip to content

Instantly share code, notes, and snippets.

@bitops
Last active August 29, 2015 14:03
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 bitops/96ab35529018278fa8c9 to your computer and use it in GitHub Desktop.
Save bitops/96ab35529018278fa8c9 to your computer and use it in GitHub Desktop.
An example implementation of Ruby's 'partition' method in Swift.
extension Array {
func partition(iterator: (T) -> Bool) -> (Array<T>, Array<T>) {
var ifTrue = Array<T>()
var ifFalse = Array<T>()
self.each {
if iterator($0) == true {
ifTrue.append($0)
} else {
ifFalse.append($0)
}
}
return (ifTrue, ifFalse)
}
}
/*
Example usage:
var numbersToPart = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var (even, odd) = numbersToPart.partition { $0 % 2 == 0 }
// even => [2, 4, 6, 8, 10]
// odd => [1, 3, 5, 7, 9 ]
*/
@bitops
Copy link
Author

bitops commented Jul 14, 2014

Depends on this 'each' implentation:

extension Array {
    func each(iterator: (T) -> Void) -> Array {
        for item in self {
            iterator(item)
        }
        return self
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment