美文网首页Swift 从入门到放弃
Swift Codable 解码为数组设定默认值

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

作者: Hank_Zhong | 来源:发表于2022-06-28 10:21 被阅读0次

通过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]
}

相关文章

网友评论

    本文标题:Swift Codable 解码为数组设定默认值

    本文链接:https://www.haomeiwen.com/subject/nhsavrtx.html