Swift - How to know when a loop has ended?
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")
}
The reason why your code doesn't work is because you have the println()
statement inside the loop, like this:
func loop() {
for var i=0; i<5; i++ {
println(i)
println("loop has finished")
}
}
So it prints out "Finished" every time the loop loops.
To fix this, all you need to do is put the println()
statement after the loop, like so:
func loop() {
for var i=0; i<5; i++ {
println(i)
}
println("loop has finished")
}
And voilà. Your app will now function properly!
func loop() {
for var i=0; i<5; i++ {
println(i)
}
println("loop has finished")
}
To produce the same result as what others have posted but with basic closure syntax:
func printFunction() {
println("loop has finished")
}
func loopWithCompletion(closure: () -> ()) {
for var i=0; i<5; i++ {
println(i)
}
closure()
}
This is how you call it:
loopWithCompletion(printFunction)
Swift 3 Update:
func printFunction() {
print("loop has finished")
}
// New for loop syntax and naming convention
func loop(withCompletion completion: () -> Void ) {
for i in 0 ..< 5 {
print(i)
}
completion()
}
Then call it like this:
loop(withCompletion: printFunction)
Or
loop {
print("this does the same thing")
}