Skip to content

Instantly share code, notes, and snippets.

@philippelatulippe
Created September 2, 2020 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philippelatulippe/e6374b54fa147aaf1e8a4a892f9ee542 to your computer and use it in GitHub Desktop.
Save philippelatulippe/e6374b54fa147aaf1e8a4a892f9ee542 to your computer and use it in GitHub Desktop.
[Swift] Decode a dictionary keyed with an enum
import Foundation
enum MyKey: String, Decodable, CodingKey {
case one
case two
}
struct Response: Decodable {
let dictionary: [MyKey: String]
}
let json = """
{
"dictionary": {
"one": "hi",
"two": "okey"
}
}
"""
let decoded = try JSONDecoder().decode(Response.self, from: json.data(using: .utf8)!)
extension KeyedDecodingContainer {
func decode(_ type: [MyKey: String].Type, forKey key: Key) throws -> [MyKey: String] {
let container = try self.nestedContainer(keyedBy: MyKey.self, forKey: key)
return try container.allKeys
.map { key in
(key: key, value: try container.decode(String.self, forKey: key))
}
.reduce(into: [MyKey: String]()) {
$0[$1.key] = $1.value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment