如何使自定义 class Codable?

How to make a custom class Codable?

我正在使用在 Github

上找到的线程安全字典

但是如何使该回购中的 ThreadSafeDictionary 符合 Codable

似乎在编码器功能中初始化一个新锁会有帮助?

您可以提供 ThreadSafeDictionary 的子类,它适用于 Codable KeyValue 类型。在我看来,最好假装我们正在处理一个简单的字典,所以让我们使用 singleValueContainer.

class CodableThreadSafeDictionary<Key: Codable & Hashable, Value: Codable>: ThreadSafeDictionary<Key, Value>, Codable {

    public required init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let dictionary = try container.decode(DictionaryType.self)
        protectedCache = CZMutexLock(dictionary)
    }

    public required init(dictionaryLiteral elements: (Key, Value)...) {
        var dictionary = DictionaryType()
        for (key, value) in elements {
            dictionary[key] = value
        }
        protectedCache = CZMutexLock(dictionary)
        super.init()
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        var dictionary = DictionaryType()
        protectedCache.readLock {
            dictionary = [=10=]
        }
        try container.encode(dictionary)
    }

}

但由于 protectedCachefileprivate 属性,您需要将此实现放在同一个文件中

注意!

您可以考虑将 Key 限制为 String 以更好地兼容 JSON 格式:

CodableThreadSafeDictionary<Key: String, Value: Codable>