在Swift中运行相同代码n次的最短方法是什么?

Evg*_*nii 49 swift

我有一个代码,我需要n在Swift中运行几次.那个最短的语法是什么?

我目前正在使用for循环,但它是很多打字.

for i in 0..<n { /* do something */ }
Run Code Online (Sandbox Code Playgroud)

是否有更短/更好的方式n在Swift中运行相同的代码时间?

Mat*_*mbo 65

说到语法,您可以定义自己的最短语法:

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
Run Code Online (Sandbox Code Playgroud)

  • 很酷,谢谢,让我想起Rails中的"5次{}".斯威夫特太棒了. (3认同)

ABa*_*ith 38

坚持for循环 - 你可以扩展Int以符合SequenceType能够写:

for i in 5 { /* Repeated five times */ }
Run Code Online (Sandbox Code Playgroud)

为了使你Int符合SequenceType你,可以做到以下几点:

extension Int : SequenceType {
    public func generate() -> RangeGenerator<Int> {
        return (0..<self).generate()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 病了!一个小点,对我来说,"我在5"将意味着我在12345而不是我在01234.(我使用psuedo关键字更像是,或许,"upTo"为01234.)当然,意见会有所不同这一点,但要记住它. (4认同)

小智 24

你有几种方法可以做到这一点:

使用for循环:

for i in 1...n { `/*code*/` }
Run Code Online (Sandbox Code Playgroud)

for i = 0 ; i < n ; i++ { `/*code*/` }
Run Code Online (Sandbox Code Playgroud)

for i in n { `/*code*/` }
Run Code Online (Sandbox Code Playgroud)

使用while循环:

var i = 0
while (i < n) {
    `/*code*/`
   ` i++`
}
Run Code Online (Sandbox Code Playgroud)

var i = 0
repeat {
   ` /*code*/`
    `i++`
} while(i <= n)
Run Code Online (Sandbox Code Playgroud)


And*_*ons 10

for _ in 1...5 {
  //action will be taken 5 times.
}
Run Code Online (Sandbox Code Playgroud)


Gre*_*Wiz 8

您可以在范围而不是循环上使用函数式编程,例如,使用较短且“更细”的语法

(0..<n).forEach{print("Index: \($0)")}
Run Code Online (Sandbox Code Playgroud)


Sun*_*kas 5

ABakerSmith 为 Swift 4 更新了答案:

extension Int: Sequence {
    public func makeIterator() -> CountableRange<Int>.Iterator {
        return (0..<self).makeIterator()
    }
}
Run Code Online (Sandbox Code Playgroud)

用:

for i in 5 {
    //Performed 5 times
}
Run Code Online (Sandbox Code Playgroud)


nie*_*bot 5

您可以执行以下操作:

10?{ print("loop") }
Run Code Online (Sandbox Code Playgroud)

在上使用自定义运算符和扩展名Int

infix operator ? // multiplication sign, not lowercase 'x'

extension Int {
    static func ?( count:Int, block: () ->Void  ) {
        (0..<count).forEach { _ in block() }
    }
}
Run Code Online (Sandbox Code Playgroud)