3

如何将 Codable 一致性添加到需要隔离到 MainActor 的类中?

例如,以下代码给出了编译器错误:

@MainActor final class MyClass: Codable {
    var value: Int
    
    enum CodingKeys: String, CodingKey {
        case value
    }
    
    init(from decoder: Decoder) throws { // <-- Compiler error: Initializer 'init(from:)' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'Decodable'
        let data = try decoder.container(keyedBy: CodingKeys.self)
        self.value = try data.decode(Int.self, forKey: .value)
    }
    
    func encode(to encoder: Encoder) throws { // <-- Compiler error: Instance method 'encode(to:)' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'Encodable'
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(value, forKey: .value)
    }
}

我现在肯定在努力让我的头脑围绕演员和@MainActor!

4

1 回答 1

2

您提供的类没有任何需要与主要参与者隔离的内容,因此不要将整个类隔离。如果您没有向我们展示的其他成员确实需要与主要演员隔离,请隔离他们。

例子:

final class MyClass: Codable {
    private var value: Int
    @MainActor init(value: Int) {
        self.value = value
    }
    @MainActor func setMyValue(to newValue:Int) {
        self.value = newValue
    }
    @MainActor func getMyValue() -> Int {
        self.value
    }
    enum CodingKeys: String, CodingKey {
        case value
    }
    init(from decoder: Decoder) throws {
        let data = try decoder.container(keyedBy: CodingKeys.self)
        self.value = try data.decode(Int.self, forKey: .value)
    }
    func encode(to encoder: Encoder) throws { // <-- Compiler error: Instance method 'encode(to:)' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'Encodable'
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(value, forKey: .value)
    }
}
于 2021-09-02T14:21:01.777 回答