Skip to content

Instantly share code, notes, and snippets.

@getaaron
Last active August 29, 2015 14:22
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 getaaron/e9d8f3180cee94a30920 to your computer and use it in GitHub Desktop.
Save getaaron/e9d8f3180cee94a30920 to your computer and use it in GitHub Desktop.
Ruby's take_while ported using a Swift 2.0 protocol extension
var source = [1, 2, 3, 4, 5, 0]
extension CollectionType {
func takeWhile(@noescape condition: (Self.Generator.Element) -> Bool) -> [Self.Generator.Element] {
var returnArray : [Self.Generator.Element] = []
for x in self {
guard condition(x) else { break }
returnArray.append(x)
}
return returnArray
}
}
let target = source.takeWhile { $0 < 3 }
print(target) // [1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment