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

后端 未结 13 2213
遥遥无期
遥遥无期 2021-02-01 00:58

I have a code that I need to run exactly n times in Swift. What is the shortest possible syntax for that?

I am currently using the for loop but

相关标签:
13条回答
  • 2021-02-01 01:03

    for-loops are a common way to repeat code. Here is an example of using a for-loop to hide six outlets, versus writing the same code for six outlets. Plus if you make another outlet all you have to do is add it to the array.

    let array = [outLet0, outlet1, outlet2, outLet3, outLet4, outLet5]
    
    for outlet in array {
      outlet.hidden = true
    }
    

    Versus writing it like this:

    outlet0.hidden = true
    outlet1.hidden = true
    outlet2.hidden = true
    outlet3.hidden = true
    outlet4.hidden = true
    outlet5.hidden = true
    
    0 讨论(0)
  • 2021-02-01 01:04

    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)
    
    0 讨论(0)
  • 2021-02-01 01:05

    Shorter and (I think) clearer:

    for i in 1...n { } // note: this will fail if n < 1
    

    or

    for i in n { }
    
    0 讨论(0)
  • 2021-02-01 01:06

    ABakerSmith's answer updated for Swift 4:

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

    Use:

    for i in 5 {
        //Performed 5 times
    }
    
    0 讨论(0)
  • 2021-02-01 01:06

    There are a lot of answers here, highlighting just how creative you can be, with Swift.

    I needed an array so I did this

    extension Int {
        func of<T>(iteration: (Int) -> T) -> [T] {
            var collection = [T]()
            for i in 0..<self {
                collection.append(iteration(i))
            }
            return collection
        }
    }
    
    fun strings() -> [String] {
        return 4.of { "\($0) teletubby" }
    }
    
    0 讨论(0)
  • 2021-02-01 01:09

    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
    
    0 讨论(0)
提交回复
热议问题