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