Evgenii Evgenii - 3 months ago 15
Swift Question

What is the shortest way to run same code n times in Swift?

I have a code that I need to run exactly

n
times in Swift. What is the shortest possible syntax for that?

I am currently using the
for
loop but it is a lot of typing.

for i in 0..<n { /* do something */ }


Is there a shorter/nicer way for running same code
n
times in Swift?

Answer

Sticking with a for loop - you could extend Int to conform to SequenceType to be able to write:

for i in 5 { /* Repeated five times */ }

To make Int conform to SequenceType you'll could do the following:

extension Int : SequenceType {
    public func generate() -> RangeGenerator<Int> {
        return (0..<self).generate()
    }
}
Comments