Created
          February 14, 2018 04:56 
        
      - 
      
- 
        Save giginet/4678c52f02f237565cb53791b1eaa949 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
    
  
  
    
  | enum Foo: String, Codable { | |
| case a | |
| case b | |
| case c | |
| } | |
| extension RawRepresentable where RawValue == String, Self: Codable { | |
| init(from decoder: Decoder) throws { | |
| var container = try decoder.unkeyedContainer() | |
| let rawValue = try container.decode(String.self) | |
| do { | |
| self.init(rawValue: rawValue)! | |
| } | |
| } | |
| func encode(to encoder: Encoder) throws { | |
| var container = encoder.unkeyedContainer() | |
| try container.encode(rawValue) | |
| } | |
| } | |
| let encoded = try? JSONEncoder().encode(Foo.a) | |
| let decoded = try? JSONDecoder().decode(Foo.self, from: encoded!) | 
      
      
  Author
  
  
        
      
            giginet
  
      
      
      commented 
        Feb 14, 2018 
      
    
  
enum Foo: String, Codable {
    case a
    case b
    case c
}
struct Hoge: Codable {
    let foo: Foo?
}
let response = """
{
"foo": "d"
}
"""
let json = response.data(using: .utf8)!
do {
    let decoded = try JSONDecoder().decode(Hoge.self, from: json)
    print("decoded value: \(decoded)")
} catch {
    print("error: \(error.localizedDescription)")
    // error: The data couldn’t be read because it isn’t in the correct format.
}
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment