Actor cannot conform to Codable?

I'm experimenting with actors under Swift 5.5. I have an actor with a single attribute, a dictionary [String: Int] . I want to make my actor conform to Codable , but since my attribute is actor-isolated, and since encode(to encoder: Encoder) is nonisolated, conforming to Codable doesn't seem possible as it requires accessing actor-isolated mutable state.

Serializing actors would seem to be a useful thing, so how does the community recommend we go about this?

final actor MyActor: Encodable {
    private var values: [String: Int]

    init(values: [String: Int]) {
        self.values = values
    nonisolated func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        let v = values // ⛔️ Actor-isolated property 'values' can not be referenced from a non-isolated context
        try container.encode(v)

I think this is currently not possible. As you say, you can either have an isolated method that doesn’t witness the Codable protocol, or a non-isolated method that can’t access the actor’s state.

SE-0313 Actor Isolation Control has as a future direction ‘isolated conformances’, which look like they would do what you need here. From within an actor isolated method/function, you would be able to encode that actor’s state.

Terms of Service

Privacy Policy

Cookie Policy