Skip to content

Instantly share code, notes, and snippets.

@HugoSay
Last active March 17, 2021 10:12
Show Gist options
  • Save HugoSay/3332a3d08c41686ad6c0726440379c10 to your computer and use it in GitHub Desktop.
Save HugoSay/3332a3d08c41686ad6c0726440379c10 to your computer and use it in GitHub Desktop.
SingleValueDecoding+DecodeIfPresent.swift
extension SingleValueDecodingContainer {
func decodeIfPresent<T>(_ type: T.Type) -> T? where T : Decodable {
print(type)
return try? decode(type)
}
}
struct MonitorStatus: Decodable {
var string: String?
var int: Int?
var bool: Bool?
init(_ s: String){
self.string = s
}
init(_ b: Bool){
bool = b
}
init(_ i: Int){
int = i
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self = try container.decodeIfPresent(String.self).map(MonitorStatus.init)
?? container.decodeIfPresent(Int.self).map(MonitorStatus.init)
?? MonitorStatus(container.decode(Bool.self))
}
}
let stringData = try JSONEncoder().encode("test")
let intData = try JSONEncoder().encode(123)
let boolData = try JSONEncoder().encode(false)
let stringStatus = try JSONDecoder().decode(MonitorStatus.self, from: stringData)
let intStatus = try JSONDecoder().decode(MonitorStatus.self, from: intData)
let boolStatus = try JSONDecoder().decode(MonitorStatus.self, from: boolData)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment