Swift - How to know when a loop has ended?

前端 未结 5 1750
我寻月下人不归
我寻月下人不归 2020-12-30 11:52

Please, forgive me as i\'m very new to swift, and programming in general.

Believe me when I say I\'ve tried hard to understand this, but I simply ca

5条回答
  •  悲&欢浪女
    2020-12-30 12:43

    Here is the loop you tried to implement:

    func loop() {
      for var i=0; i<5; i++ {
        println(i)
        println("loop has finished")
      }
    }
    

    The reason why "loop has finished" gets printed 5 times is because it is within the for-loop.

    Anything in between your brackets will be run when the loop repeats (where I entered "enter code here)

    for var i=0; i<5; i++ {
       enter code here
     }
    

    The way that loops work is, it will repeat until the condition is completed: i.e. i<5. Your i variable starts at 0 as you stated in var i=0, and every time the loop repeats, this number increases by 1, as stated in i++

    Once i is not less than 5 (i is equal to 5 or greater than 5), then the code following your for-loop will be run.

    So if you put your println("loop has finished") right after the forloop, you know it will run when the loop is completed, like this:

    func loop() {
      for var i=0; i<5; i++ {
        println(i)
      }
      println("loop has finished")
    }
    

提交回复
热议问题