Skip to content

Instantly share code, notes, and snippets.

@giginet
Created February 14, 2018 04:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giginet/4678c52f02f237565cb53791b1eaa949 to your computer and use it in GitHub Desktop.
Save giginet/4678c52f02f237565cb53791b1eaa949 to your computer and use it in GitHub Desktop.
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!)
@giginet
Copy link
Author

giginet commented Feb 14, 2018

struct Hoge: Codable {
    let foo: Foo?

    enum CodingKeys: String, CodingKey {
        case foo
    }
}

@bannzai
Copy link

bannzai 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