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

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(@autoclosure f: () -> ()) {
        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

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

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)

Tags:

Swift