Guest User

Untitled

a guest
Jul 18th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. public struct AnyCodable {
  2. let value: Any
  3.  
  4. public init(_ value: Any) {
  5. self.value = value
  6. }
  7. }
  8.  
  9. extension AnyCodable: Codable {
  10. public init(from decoder: Decoder) throws {
  11. let container = try decoder.singleValueContainer()
  12. if let v = try? container.decode(String.self) {
  13. self.value = v
  14. return
  15. }
  16. if let v = try? container.decode(Int.self) {
  17. self.value = v
  18. return
  19. }
  20. if let v = try? container.decode(Double.self) {
  21. self.value = v
  22. return
  23. }
  24. if let v = try? container.decode(Float.self) {
  25. self.value = v
  26. return
  27. }
  28. if let v = try? container.decode(Bool.self) {
  29. self.value = v
  30. return
  31. }
  32. fatalError("Given type is not supported")
  33. }
  34.  
  35. public func encode(to encoder: Encoder) throws {
  36. var container = encoder.singleValueContainer()
  37. switch value {
  38. case let v as String: try container.encode(v)
  39. case let v as Int: try container.encode(v)
  40. case let v as Double: try container.encode(v)
  41. case let v as Float: try container.encode(v)
  42. case let v as Bool: try container.encode(v)
  43. default: fatalError("Type \(type(of: value)) not supported")
  44. }
  45. }
  46. }
  47.  
  48. extension AnyCodable: ExpressibleByStringLiteral {
  49. public init(stringLiteral value: String) {
  50. self.value = value
  51. }
  52. }
  53.  
  54. extension AnyCodable: ExpressibleByIntegerLiteral {
  55. public init(integerLiteral value: Int) {
  56. self.value = value
  57. }
  58. }
  59.  
  60. extension AnyCodable: ExpressibleByFloatLiteral {
  61. public init(floatLiteral value: Float) {
  62. self.value = value
  63. }
  64. }
  65.  
  66. extension AnyCodable: ExpressibleByBooleanLiteral {
  67. public init(booleanLiteral value: Bool) {
  68. self.value = value
  69. }
  70. }
Add Comment
Please, Sign In to add comment