GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.