BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

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()
        }
    }
}

   

@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()
        }
    }
}

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.