'For Loop wait and delay - Swift 4

I have a nested for loop, and am trying to make it so that the outer loop will only continue once the inner loop and its code is completed, and also add a 1 second delay before performing the next loop.

    for _ in 0...3 {
        for player in 0...15 {
            // CODE ADDING MOVEMENTS TO QUEUE
        }
        updateBoardArray()
        printBoard()

        // NEED TO WAIT HERE FOR 1 SEC
    }

So I wan't the 0...3 For loop to progress only once the inner loop and update and print functions have completed their cycle, and also a 1 second wait time.

At the moment it all happens at once and then just prints all 4 boards instantly, even when I put that 1 second wait in using DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {}.

Have tried other answers to similar questions but can't seem to get it to work.



Solution 1:[1]

asyncAfter() function takes DispatchTime. DispatchTime is in nanosecond. Following is prototype:

func asyncAfter(deadline: DispatchTime, execute: DispatchWorkItem)

Following is extract of docs from Apple Developer webpage:

DispatchTime represents a point in time relative to the default clock with nanosecond precision. On Apple platforms, the default clock is based on the Mach absolute time unit

To solve the problem, use:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1000) {}

Solution 2:[2]

You can use scheduledTimer:

for i in 0..3{
    Timer.scheduledTimer(withTimeInterval: 0.2 * Double(i), repeats: false) { (timer) in
        //CODE
    }
}

More Info about scheduledTimer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ouflak