Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public struct AnyCodable {
- let value: Any
- public init(_ value: Any) {
- self.value = value
- }
- }
- extension AnyCodable: Codable {
- public init(from decoder: Decoder) throws {
- let container = try decoder.singleValueContainer()
- if let v = try? container.decode(String.self) {
- self.value = v
- return
- }
- if let v = try? container.decode(Int.self) {
- self.value = v
- return
- }
- if let v = try? container.decode(Double.self) {
- self.value = v
- return
- }
- if let v = try? container.decode(Float.self) {
- self.value = v
- return
- }
- if let v = try? container.decode(Bool.self) {
- self.value = v
- return
- }
- fatalError("Given type is not supported")
- }
- public func encode(to encoder: Encoder) throws {
- var container = encoder.singleValueContainer()
- switch value {
- case let v as String: try container.encode(v)
- case let v as Int: try container.encode(v)
- case let v as Double: try container.encode(v)
- case let v as Float: try container.encode(v)
- case let v as Bool: try container.encode(v)
- default: fatalError("Type \(type(of: value)) not supported")
- }
- }
- }
- extension AnyCodable: ExpressibleByStringLiteral {
- public init(stringLiteral value: String) {
- self.value = value
- }
- }
- extension AnyCodable: ExpressibleByIntegerLiteral {
- public init(integerLiteral value: Int) {
- self.value = value
- }
- }
- extension AnyCodable: ExpressibleByFloatLiteral {
- public init(floatLiteral value: Float) {
- self.value = value
- }
- }
- extension AnyCodable: ExpressibleByBooleanLiteral {
- public init(booleanLiteral value: Bool) {
- self.value = value
- }
- }
Add Comment
Please, Sign In to add comment