I know I can delay a part of code in Swift 3 using the followign syntax (How to program a delay in Swift 3):
let when = DispatchTime.now() + 2 // change 2 to desired second delay.
DispatchQueue.main.after(when: when) {
// run your code with delay
}
Or a similar post: How to create dispatch queue in Swift 3
However these are not the delay methods I could use. I need to insert a delay in the loop. For example imagine that there's a label component and a button. When I click the button, I want the label to show the loop variable consecutively:
@IBOutlet weak var showIntegers: UILabel!
@IBAction func countNums(_ sender: AnyObject) {
for i in 1...5 {
showIntegers.text = String(i)
//delay code here, sleep(1) doesn't work
}
}
I used sleep as the delay but then the app sleeps for 5 seconds and then displays 5. I cannot see 1, 2, 3, 4 and 5 consecutively with 1 seconds of delay.
I also couldn't figure out how I can use the DispatchQueue class inside the loop. Thanks for your help in advance.