Created
July 31, 2021 05:36
-
-
Save manhpham90vn/197b1fc5350bd6778ce9bc730e688657 to your computer and use it in GitHub Desktop.
DynamicJSONProperty.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum DynamicJSONProperty: Codable { | |
case int(Int) | |
case double(Double) | |
case string(String) | |
var intValue: Int? { | |
switch self { | |
case let .int(value): | |
return value | |
case let .double(value): | |
return Int(value) | |
case let .string(value): | |
return Int(value) | |
} | |
} | |
var stringValue: String? { | |
switch self { | |
case let .int(value): | |
return String(value) | |
case let .double(value): | |
return String(value) | |
case let .string(value): | |
return value | |
} | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
if let intValue = try? container.decode(Int.self) { | |
self = .int(intValue) | |
return | |
} | |
if let doubleValue = try? container.decode(Double.self) { | |
self = .double(doubleValue) | |
return | |
} | |
if let stringValue = try? container.decode(String.self) { | |
self = .string(stringValue) | |
return | |
} | |
throw DecodingError.typeMismatch(DynamicJSONProperty.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for DynamicJSONProperty")) | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
switch self { | |
case .double(let value): | |
try container.encode(value) | |
case .string(let value): | |
try container.encode(value) | |
case .int(let value): | |
try container.encode(value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment