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

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

提交回复
热议问题