【发布时间】:2021-10-13 20:59:16
【问题描述】:
如何将 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!
【问题讨论】:
-
我最初发布了一个我发现错误的答案 - 使
init(from decoder: Decoder)async将允许MyClass符合Decodable,但我无法得到 @987654326 @遵守工作。 -
不,因为那些
async函数与 Encodable 想要调用的函数不同。
标签: swift concurrency swiftui swift-concurrency