Skip to content

Instantly share code, notes, and snippets.

@s0nerik
Created July 18, 2018 07:45
Show Gist options
  • Save s0nerik/8c94acb580b978f3553e6d57c6e0590c to your computer and use it in GitHub Desktop.
Save s0nerik/8c94acb580b978f3553e6d57c6e0590c to your computer and use it in GitHub Desktop.
AnyCodable
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment