ios – The behavior of Task seems to differ in Playground environments


In an actual app project, when running the following code, the print statements occur in the order of 1->3->2:

var body: some View {
    Text
    .onAppear {
        print("1")
        Task {
            print("2")
        }
        print("3")
    }
}

However, when executing the equivalent code in Playground, the print statements occur in the order of 1->2->3:

print("1")
Task {
    print("2")
}
print("3")

After conducting several tests in the Playground environment, I observed that running the function inside Task on the mainActor or lowering the priority of the Task significantly (e.g., .background) results in order of 1->3->2:

print("1")
Task { @MainActor in
    print("2")
}
print("3")

// or
print("1")
Task(priority: .background) {
    print("2")
}
print("3")

However, without these additional configuration, I believe that the print order in Playground also should be 1->3->2.

Could you please explain why in Playground the execution order is 1->2->3?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img