Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created Nov 6, 2016
Embed
What would you like to do?
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