Skip to content

Instantly share code, notes, and snippets.

@reckenrode
Created June 23, 2017 19:49
Show Gist options
  • Save reckenrode/9acbd7200cff3590bda5e83118f62523 to your computer and use it in GitHub Desktop.
Save reckenrode/9acbd7200cff3590bda5e83118f62523 to your computer and use it in GitHub Desktop.
Implement Codable on an enum
struct User: Codable {
var name: String
var email: String
var id: String
var metadata: [String: MetadataType]
enum CodingKeys: String, CodingKey {
case name, email, id, metadata
}
}
enum MetadataType: Codable {
case double(Double)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = try .double(container.decode(Double.self))
} catch DecodingError.typeMismatch {
do {
self = try .string(container.decode(String.self))
} catch DecodingError.typeMismatch {
throw DecodingError.typeMismatch(MetadataType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded payload not of an expected type"))
}
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .double(let double):
try container.encode(double)
case .string(let string):
try container.encode(string)
}
}
}
import Foundation
let decoder = JSONDecoder()
let userJson = """
{
"id": "4yq6txdpfadhbaqnwp3",
"email": "[email protected]",
"name":"John Doe",
"metadata": {
"link_id": "linked-id",
"buy_count": 4
}
}
""".data(using: .utf8)!
let user = try! decoder.decode(User.self, from: userJson)
print(user)
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
let plist = try! encoder.encode(user)
print(String(data: plist, encoding: .utf8)!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment