I am trying to process over an array of simple elements, where on every element of the array a time-consuming process of updating the UI with a Timer will be started. The order of the elements in the array is important and matters. For simplicity sake I simplified the code down to this:
func processArray() {
let signals = [0, 1, 0, 1, 1]
for element in signals {
//pause and process first element
timeConsumingProcess(e: element)
//after processing first element finished, continue to next element
}
}
func timeConsumingProcess(e: Int) {
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { timer in
// 2 seconds set for demonstration purposes, can take more or less depending on the element
// doing something with e in UI
timer.invalidate()
}
}
How can I pause array iteration while the time consuming timeConsumingProcess(e: Int)
is happening?
I tried using OperationQueues, DispatchGroups, DispatchSerialQueues, sync{}
blocks, but to no avail. I’m guessing with the advancement of Swift concurrency and Async/Await
there should be an elegant and efficient solution to it, but I just can’t wrap my head around it. Sequentially processing time-consuming events has never been easy in Swift, but I’m entirely at a loss here, so any help would be greatly appreciated!