Hi, I have two questions about nonisolated after reading SE-0313. I'd appreciate any explanations or comments.
Q1: Why is it OK to apply nonisolated to a global variable?
IIUC nonisolated was introduced to allow accessing to actor's property or method synchronously from outside the actor. So I thought it's only supposed to be used inside actor. However, I find the following code compiles:
final class SomeClass: Sendable {
let x = 1
}
nonisolated let g = SomeClass() // This compiles
I wonder what's the effect of nonisolated modifier in the above code?
Q2: On which executor is a nonisolated method executed?
At first I thought that a nonisolated method is executed on global pool (the global executor). However, in the followinng code I'm able to access a nonisolated method synchronously from within the actor, which I think indicates nonisolated method is executed on the actor's executor. On the other hand, the fact that one is able to access an actor's nonisolated property and method synchronously from outside the actor indicates that they are executed in global executor. So, does it mean where a nonisolated method is executed depends on the caller?
final class SomeClass: Sendable {
let x = 1
}
actor BankAccount {
nonisolated let o = SomeClass()
nonisolated func f1() -> SomeClass {
o
}
func f2() -> SomeClass {
// It's OK to access nonisolated property and method synchronously
// from within the actor
let _ = o
return f1()
}
}
func test() {
let account = BankAccount()
// It's OK to access an actor's nonisolated property and method synchronously
// from outside the actor (this is why it was introduced in SE-0313).
print(account.f1().x)
}
EDIT: for the second question, I find the answer in SE-0420:
Non-isolated synchronous functions dynamically inherit the isolation of their caller.