如何将 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/