Search code examples
swiftswift-concurrency

Swift Concurrency - Why my Task didn't inherit the parent Task's executor and priority


When creating Task A from Task B, I thought Task A will inherit from Task B. But when running the following code I created, why did line 14 printed debug 4: <NSThread: 0x30361a300>{number = 6, name = (null)}. Why it isn't main thread, just like the other prints?

enter image description here

Here's the code for anyone who wants to run locally:

struct Test {
    func test() {
        print("debug 3:", Thread.current)
        Task {
            print("debug 4:", Thread.current)
        }
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        Task { @MainActor in
            print("debug 1:", Thread.current)
            Task {
                print("debug 2:", Thread.current)
                Test().test()
            }
        }
    }
}

Solution

  • The function test is not actor-isolated. Thus, its Task {…} is not actor-isolated either. (If test was actor-isolated, then its Task {…} would be a top level task on the same actor. But test not actor-isolated, so that is moot.)

    In Swift concurrency, a function’s isolation is either explicitly defined or inherited from the type in which it is defined, if any, but it does not “inherit” it from the caller.