Last active
March 15, 2018 16:23
-
-
Save harrytwright/80ee941353abdd8dfd0cc87e87653c6b to your computer and use it in GitHub Desktop.
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
extension AnyCodable: Codable { | |
public init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
if let intValue = try? container.decode(Int.self) { | |
self._box = _ConcreteCodableBox<Int>(intValue) | |
} else if let doubleValue = try? container.decode(Double.self) { | |
self._box = _ConcreteCodableBox<Double>(doubleValue) | |
} else if let floatValue = try? container.decode(Float.self) { | |
self._box = _ConcreteCodableBox<Float>(floatValue) | |
} else if let stringValue = try? container.decode(String.self) { | |
self._box = _ConcreteCodableBox<String>(stringValue) | |
} else if let dictionaryValue = try? container.decode([String:AnyCodable].self) { | |
self._box = _ConcreteCodableBox<[String:AnyCodable]>(dictionaryValue) | |
} else if let arrayValue = try? container.decode([AnyCodable].self) { | |
self._box = _ConcreteCodableBox<[AnyCodable]>(arrayValue) | |
} else { | |
throw DecodingError.typeMismatch( | |
type(of: self), | |
.init( | |
codingPath: decoder.codingPath, | |
debugDescription: "Unsupported JSON type" | |
) | |
) | |
} | |
} | |
public func encode(to encoder: Encoder) throws { | |
// Safe to use `as!` becasue the `_base` is just `_baseCodable` | |
try (self._box._base as! Codable).encode(to: encoder) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment