Actor subscript can not be mutated

Viewed 83

I have this actor:

public actor MyActor {
    private var array: [String] = []

    public subscript(index: Int) -> String {
        get {
            array[index]
        }
        set {
            array[index] = newValue
        }
    }
}

But when I try to use the subscript like this:

let myActor = MyActor()

Task {
    await myActor[0] = "foo" // compilation error on this line
}

I get this compilation error:

Actor-isolated subscript 'subscript(_:)' can not be mutated from a non-isolated context

How can I use the subscript method on an actor?

1 Answers

The error you are getting isn't specific to subscript, you can get the same error if you make array property public and try to set it the same way outside the actor.

This error is because unlike get, set accessor in swift doesn't support async specifier as of now. So when you are trying to set the property from outside the actor, the compiler is giving error as you are calling an actor isolated method synchronously outside the actor.

Your only option as of now is to create a new method to update data and call that outside of actor instead:

public actor MyActor {
    public var array: [String] = []

    public subscript(index: Int) -> String {
        get {
            array[index]
        }
        set {
            array[index] = newValue
        }
    }

    public func setItem(_ item: String, at index: Int) {
        array[index] = item
    }
}

let myActor = MyActor()

Task {
    await myActor.setItem("foo", at: 0)
}
Related