Created
September 2, 2020 14:25
-
-
Save philippelatulippe/e6374b54fa147aaf1e8a4a892f9ee542 to your computer and use it in GitHub Desktop.
[Swift] Decode a dictionary keyed with an enum
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
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