TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your 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.