Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the `nonisolated` keyword in Swift?

Tags:

swift

actor

I recently came across the nonisolated keyword in Swift in the following code:

actor BankAccount {

    init(balance: Double) {
        self.balance = balance
    }

    private var balance: Double

    nonisolated func availableCountries() -> [String] {
        return ["US", "CA", "NL"]
    }

    func increaseBalance(by amount: Double) {
        self.balance += amount
    }

}

What does it do? The code compiles both with and without it.

like image 321
Flying Oyster Avatar asked Dec 28 '25 06:12

Flying Oyster


1 Answers

The nonisolated keyword was introduced in SE-313. It is used to indicate to the compiler that the code inside the method is not accessing (either reading or writing) any of the mutable state inside the actor. This in turn, enables us to call the method from non-async contexts.

The availableCountries() method can be made nonisolated because it doesn't depend on any mutable state inside the actor (for example, it doesn't depend on the balance variable).

When you are accessing different methods or variables of an actor, from outside the actor, you are only able to do so from inside an asynchronous context.

Let's remove the nonisolated keyword from the availableCountries() method. Now, if we want to use the method, we are only allowed to do so in an async context. For example, inside a Task:

let bankAccount = BankAccount(balance: 1000)

override func viewDidLoad() {
    super.viewDidLoad()

    Task {

        let availableCountries = await bankAccount.availableCountries()
        print(availableCountries)

    }

}

If we try to use the method outside of an async context, the compiler gives us errors:

Compiler Error

However, the availableCountries() isn't using any mutable state from the actor. Thus, we can make it nonisolated, and only then we can call it from non async contexts (and the compiler won't nag).

enter image description here

like image 55
Flying Oyster Avatar answered Dec 30 '25 21:12

Flying Oyster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!