Guest User

Untitled

a guest
Feb 25th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. enum Foo: String, Codable {
  2. case a
  3. case b
  4. case c
  5. }
  6.  
  7. extension RawRepresentable where RawValue == String, Self: Codable {
  8. init(from decoder: Decoder) throws {
  9. var container = try decoder.unkeyedContainer()
  10. let rawValue = try container.decode(String.self)
  11. do {
  12. self.init(rawValue: rawValue)!
  13. }
  14. }
  15.  
  16. func encode(to encoder: Encoder) throws {
  17. var container = encoder.unkeyedContainer()
  18. try container.encode(rawValue)
  19. }
  20. }
  21.  
  22. let encoded = try? JSONEncoder().encode(Foo.a)
  23. let decoded = try? JSONDecoder().decode(Foo.self, from: encoded!)
Add Comment
Please, Sign In to add comment