swift - 使@MainActor 类或 Actor 符合 Codable

标签 swift concurrency swiftui swift-concurrency

如何将 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)
    }
}
我现在肯定正在努力了解 Actor 和@MainActor!

最佳答案

您提供的类没有任何需要与主要参与者隔离的内容,因此不要将类作为一个整体进行隔离。如果还有其他您没有向我们展示的成员确实需要与主要 Actor 隔离,请将他们隔离。
例子:

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)
    }
}

关于swift - 使@MainActor 类或 Actor 符合 Codable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68724382/

相关文章:

arrays - 如何在 Swift 3 中向结构数组添加新变量?

java - 两个线程死锁但不明白为什么,用 notifyAll() 释放了锁

swift - 属性更改时的动画 View SwiftUI

ios - 使用 ForEach 在 SwiftUI 中按下按钮时制作独特的工作表?

navigationview - SwiftUI - ObservableObject 创建了多次

ios - 自定义对象数组 - Swift

ios - 在 UITableView 中创建子部分(Swift 2.3)

javascript - Nodejs 文件流并发

java - 并发系统中读取ArrayList

xcode - Swift,无法使用类型的参数列表调用 objc_setAssociatedObject