Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created November 6, 2016 20:52
Show Gist options
  • Select an option

  • Save khanlou/22ed5f66be4c41910eef2bf658d8ec27 to your computer and use it in GitHub Desktop.

Select an option

Save khanlou/22ed5f66be4c41910eef2bf658d8ec27 to your computer and use it in GitHub Desktop.
Ruby's n.times in Swift
extension SignedInteger {
func times() -> AnySequence<()> {
return AnySequence<()>({ () -> AnyIterator<()> in
var count: Self = 0
return AnyIterator<()>({
if count == self {
return nil
}
defer { count = count + 1 }
return ()
})
})
}
func timesWithIndex() -> AnySequence<Self> {
return AnySequence<Self>({ () -> AnyIterator<Self> in
var count: Self = 0
return AnyIterator<Self>({
if count == self {
return nil
}
defer { count = count + 1 }
return count
})
})
}
}
5.times().forEach {
print("hi")
}
5.timesWithIndex().forEach { i in
print("hey", i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment