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

后端 未结 13 2214
遥遥无期
遥遥无期 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:12

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

    In Swift, what you have is the shortest syntax for performing a loop operation.

    Swift provides two kinds of loop that perform a set of statements a certain number of times:

    The for-in loop performs a set of statements for each item in a sequence.

    The for loop performs a set of statements until a specific condition is met.

    If you want to run it infinite times, well try using a while.

    0 讨论(0)
  • 2021-02-01 01:15

    ONLY 5 CHARACTERS (not including n or code)

    r(){}
    

    If you're just testing things and need a REALLY short line, try this. Emphasis on using this for testing, not in production, because no one will know what is going on without documentation.

    define this somewhere globally

    func r(_ n : UInt, _ c: @escaping () -> Void) { for _ in 0..<n { c() } }
    

    call this when you want to run it

    r(5) { /*code*/ }
    
    0 讨论(0)
  • 2021-02-01 01:17

    You could do something like this:

    10⨉{ print("loop") }
    

    Using a custom operator and an extension on Int:

    infix operator ⨉ // multiplication sign, not lowercase 'x'
    
    extension Int {
        static func ⨉( count:Int, block: () ->Void  ) {
            (0..<count).forEach { _ in block() }
        }
    }
    
    0 讨论(0)
  • 2021-02-01 01:19
    for _ in 1...5 {
      //action will be taken 5 times.
    }
    
    0 讨论(0)
  • 2021-02-01 01:23

    you could use functional programming on a range instead of a loop, for shorter and "nicer" syntax for example

    (0..<n).forEach{print("Index: \($0)")}
    

    Other answers mention defining your own syntax for that. So - that can be fine for a tiny personal project, or as a learning experience. But defining your own syntax for something so trivial and basic in a large project would be maintenance and readability hell.

    0 讨论(0)
提交回复
热议问题