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

Waiting until the for loops ends

Forums > Swift

The second question I have isn't related to the first, even though I'm using the same test project (At the time of this writing, they are next to each other). I would like to use a print statement before the runAll function starts, and when all the one() functions finish, I would like to print another statement. The function one() doesn't return anything. It goes out and does some work. This test app just waits 5 seconds. The real use does the same thing, goes out and does some work and doesn't return anything. I've done some reading on TestGroup, but that seems to have to return something. I've yet to be able to duplicate that sort of thinking, but without returning anything, or returning something I don't actually care about.

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()
            } // When all 5 of the one() functions finish, I want to print("The loop has ended")
        }
    }

    func one() async { // I'm not returning anything.  I go off and do some work
        print("Start one")
        delayWithSeconds(5) {
           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 your entire paywall view without any code changes or app updates.

Learn more here

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.