Evgenii Evgenii - 1 year ago 89
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

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

I am currently using the
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
times in Swift?

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download