UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Async Await with a For Loop

Forums > Swift

Posted below is just a test app. The premise is that I'm trying is to go through an array, each time running code that may take a second to run. I would like the function to start and finish before the next one starts. It does not return anything. With the current code, it starts the function 5 times "all at once", then finishes "at the same time". I would like the output to be "Start one", "End one", then "Start one" "End one"...

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("RunAll")
        }
        .onTapGesture {
            runAll()
        }
        .padding()
        .font(.largeTitle)
    }

    func runAll() {
        print("Here is the loop")
        for _ in 1...5 {
            Task {
                await one()
            }
        }
    }

    func one() async {
        print("Start one")
        delayWithSeconds(5) {
           print("End one")
        }
    }

    func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
            completion()
        }
    }
}

3      

@Bnerd  

A simple approach:

struct ContentView: View {

    @State private var loadStatus: Bool =  false // We will monitor the toggling
    @State private var itemsLoaded = 0 // Follows up what is loaded

    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("RunAll")
        }
        .onTapGesture {
            print("Here is the loop")
            runAll()
        }
        .onChange(of: loadStatus, perform: { _ in // Added
            if itemsLoaded <= 5 - 1 { // 5 is Your array Count
            runAll()
        }
        })
        .padding()
        .font(.largeTitle)
    }

    func runAll() { //Modified

            Task {
                await one()
            }
    }

    func one() async {
        print("Start one")
        delayWithSeconds(5) {
            itemsLoaded += 1
            loadStatus.toggle()
           print("End one")
        }
    }

    func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
            completion()
        }
    }
}

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.