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

You have several ways of doing that:

Using for loops:

for i in 1...n { `/*code*/` }

for i = 0 ; i < n ; i++ { `/*code*/` }

for i in n { `/*code*/` }

using while loops:

var i = 0
while (i < n) {
    `/*code*/`
   ` i++`
}

var i = 0
repeat {
   ` /*code*/`
    `i++`
} while(i <= n)

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()
    }
}

Speaking of syntax, you might define your own shortest syntax:

extension Int {
    func times(_ f: () -> ()) {
        if self > 0 {
            for _ in 0..<self {
                f()
            }
        }
    }
    
    func times(_ f: @autoclosure () -> ()) {
        if self > 0 {
            for _ in 0..<self {
                f()
            }
        }
    }
}

var s = "a"
3.times {
    s.append(Character("b"))
}
s // "abbb"


var d = 3.0
5.times(d += 1.0)
d // 8.0

Tags:

Swift