Actor-isolated property can not be referenced from a non-isolated context

I was in need some days back to create a mock that conformed to an Actor protocol. And when trying to accessing one of their properties I couldn’t do it. And the error that you see on the title of this post was showed. This was an obvious thing that I found out after reading the Actor text again.

When using Actors, you need to understand that they will provide you with a mechanism to isolate their state from the rest of the program. If we read the documentation:

An actor is a reference type that protects access to its mutable state. They protect their state from data races.

Actor isolation is how actors protect their mutable state. For actors, the primary mechanism for this protection is by only allowing their stored instance properties to be accessed directly on self

https://github.com/apple/swift-evolution/blob/main/proposals/0306-actors.md

I was trying then to access a property of my mock that was in the end an Actor type like:

mock.deleteCallsCount

 This is invalid, and the only way to access this property is through a function inside the Actor class that will then access the property value.

public actor MyMock: SomeProtocol  {
    
     var deleteCallsCount = 0
     var deleteCalled = false

    public func deleteCallsCount() -> Int {
        deleteCallsCount
    }
    
    public func deleteCalled() -> Bool {
        deleteCalled
    }
}


And finally, we need to use the await before the call of the method

let resultCallsCount = await myMock.deleteCallsCount()

let resultCalled = await myMock.deleteCalled()

In this way we can access our Actor property avoiding data races and the invalid message from the compiler.

 

Sofia Swidarowicz

I'm an iOS Software Engineer mostly. Known as phynet in the internez. I'm me, full of memory failure and lovely karma.

 

Leave a Reply

Your email address will not be published. Required fields are marked *