所以基本上我想要的是任何时候API返回的类型不同于模型期望使该属性为空的类型。
例如:
struct Person {
var name: String?
var someType: String?
}
如果API为someType属性返回一个数字,而不是一个字符串,我只想让它的值为nil
我知道我可以实现init(from decoder: Decoder)
初始化器,但是我必须为每个响应的每个属性设置它,这将花费很长的时间。有没有更好更快的方法?
发布于 2020-10-14 21:54:58
您可以为可选字符串实现自己的decodeIfPresent,如果类型不匹配,则返回nil。这样你就不必实现一个自定义的初始化器:
extension KeyedDecodingContainer {
public func decodeIfPresent(_ type: String.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> String? {
do {
return try decode(String.self, forKey: key)
} catch DecodingError.typeMismatch, DecodingError.keyNotFound {
return nil
}
}
}
struct Person: Decodable {
let name: String?
let someType: String?
}
let json = #"{"name":"Steve","someType":1}"#
do {
let person = try JSONDecoder().decode(Person.self, from: Data(json.utf8))
person.name // "Steve"
person.someType // nil
} catch {
print(error)
}
https://stackoverflow.com/questions/64361825
复制相似问题