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(_ 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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)