struct User: Codable {
var name: String
/// 可兼容服务器返回的Int 或者String类型
@CNString public var age: String?
}
/// 将 String Int 解析为 String? 的包装器
@propertyWrapper public struct CNString: Codable {
public var wrappedValue: String?
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
var string: String?
do {
string = try container.decode(String.self)
} catch {
do {
string = try String(container.decode(Int.self))
} catch {
string = nil
}
}
wrappedValue = string
}
}
Swift Codable 解析不确定类型
最新推荐文章于 2023-04-25 20:28:51 发布