Swift Codable 解码为数组设定默认值

通过onevcat《使用 Property Wrapper 为 Codable 解码设定默认值》文章内容我们可以为基础类型设定默认值。这里参照给出为数组设定默认值的方法:

@propertyWrapper
struct DefaultArray<Element: Codable>: Codable {
    var wrappedValue: [Element]
}

extension DefaultArray {
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        wrappedValue = (try? container.decode([Element].self)) ?? [Element]()
    }
}

extension KeyedDecodingContainer {
    func decode<E>(
        _ type: DefaultArray<E>.Type,
        forKey key: Key
    ) throws -> DefaultArray<E>  {
        try decodeIfPresent(type, forKey: key) ?? DefaultArray(wrappedValue: [E]())
    }
}

使用:

struct ExampleModel: Codable {
    @DefaultArray
    var hank: [String]
    @DefaultArray
    var zhy: [ZhyModel]
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容