Skip to content

Instantly share code, notes, and snippets.

@js
Last active April 29, 2022 14:23
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 js/d9035a03bab729092f55ec9a57d037fa to your computer and use it in GitHub Desktop.
Save js/d9035a03bab729092f55ec9a57d037fa to your computer and use it in GitHub Desktop.
import UIKit
let json1 = """
{"results": [{"name": "bob"}]}
""".data(using: .utf8)!
let json2 = """
{"people": [{"name": "Jane"}]}
""".data(using: .utf8)!
struct Person: Decodable {
let name: String
}
protocol ResultContainerCodingKey: CodingKey {
static var resultCodingKey: String { get }
init()
}
extension ResultContainerCodingKey {
init() {
self.init()
}
// MARK: CodingKey impl
var intValue: Int? { nil }
init?(intValue: Int) {
return nil // unused
}
var stringValue: String {
Self.resultCodingKey
}
init?(stringValue: String) {
return nil
}
}
struct ResultsContainerCodingKey: ResultContainerCodingKey {
static var resultCodingKey = "results"
}
struct PeopleContainerCodingKey: ResultContainerCodingKey {
static var resultCodingKey = "people"
}
struct ResultsContainer<ResultKey, ResultType>: Decodable where ResultKey: ResultContainerCodingKey, ResultType: Decodable {
let results: ResultType
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ResultKey.self)
results = try container.decode(ResultType.self, forKey: ResultKey())
}
}
let decodedResult1 = try! JSONDecoder().decode(ResultsContainer<ResultsContainerCodingKey, [Person]>.self,
from: json1)
decodedResult1.results
let decodedResult2 = try! JSONDecoder().decode(ResultsContainer<PeopleContainerCodingKey, [Person]>.self,
from: json2)
decodedResult2.results
// uncomment to see decoding errors when keys don't exist in the json data:
//let decodedResult3 = try! JSONDecoder().decode(ResultsContainer<ResultsContainerCodingKey, [Person]>.self, from: json2)
//decodedResult3.results
//let decodedResult4 = try! JSONDecoder().decode(ResultsContainer<PeopleContainerCodingKey, [Person]>.self, from: json1)
//decodedResult4.results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment