dan martin dan martin - 1 month ago 9
Swift Question

Swift - How to know when a loop has ended?

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 can't and would greatly appreciate any help.

say I have this function:

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


and I wanted to print to the logs "loop has finished" once this loop had completed and finished running, how would I do this? If i do:

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


then "loop has finished" gets printed after every time i is incremented.

I've tried reading into closures and completion handlers, but it's all going over my head at the moment and I don't really understand how i'd achieve the task above.

If there's an angel that can show me how I'd complete my above example, I'd be in your debt.

Thankyou for your patience with my currently pathetic knowledge!

Answer

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")
}
Comments