轻松处理 Codable 类型默认值:DefaultCodable

DefaultCodable 是一个轻量级的 Swift 工具包,可以轻松地为 Codable 类型中缺失或为 nil 的属性设置默认值。

例如,假设我们有一个 Apple 产品模型,其中只有 name 属性是必需的:

enum ProductType: String, Codable, CaseIterable {
    case phone, pad, mac, accessory
}

struct Product: Codable {
    var name: String
    var description: String?
    var isAvailable: Bool?
    var type: ProductType?
}

通过使用 @Default 属性包装器,我们可以为可选属性提供默认值,从而简化模型:

struct Product: Codable {
    var name: String
    @Default("") var description: String
    @Default(false) var isAvailable: Bool
    @Default(.phone) var type: ProductType
}
zip 文件大小:8.64KB