Skip to content

Instantly share code, notes, and snippets.

@woolsweater
Created February 7, 2020 21:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woolsweater/ebfd7d5edc589a878c6ad6f457d01640 to your computer and use it in GitHub Desktop.
Save woolsweater/ebfd7d5edc589a878c6ad6f457d01640 to your computer and use it in GitHub Desktop.
import Foundation
/**
A decodable type that expects its data to be enclosed in a
keyed container.
For example, using JSON, a `User` object might be delivered
inside another object, with `"user"` as the key:
```
{ "user" : { "name" : "Alice", "rank" : "Colonel" } }
```
*/
protocol EnvelopeDecodable : Decodable {
/** The key for this type in the enclosing container. */
static var contentsKey: String { get }
}
/**
Decodable representation for another decodable type
that is delivered as a nested object in a keyed container.
*/
struct Envelope<T : EnvelopeDecodable> : Decodable {
/** The wrapped value that we actually want to extract. */
let contents: T
private enum CodingKeys : CodingKey {
case contents
var stringValue: String { T.contentsKey }
}
}
// Example:
struct User : EnvelopeDecodable {
static let contentsKey = "user"
let name: String
let rank: String
let favoriteCereal: String
}
let json = """
{
"user" : {
"name" : "Alice",
"rank" : "Colonel",
"favoriteCereal" : "Corn flakes"
}
}
""".data(using: .utf8)!
let response = try! JSONDecoder().decode(Envelope<User>.self, from: json)
print(response.contents) // User(name: "Alice", rank: "Colonel", favoriteCereal: "Corn flakes")
@woolsweater
Copy link
Author

woolsweater commented Feb 7, 2020

JSON responses sometimes come with this wrapper level around the object that we actually care about, which can be annoying to deal with in the Codable world. A common technique to handle it is to make a Decodable helper type that represents that wrapper, so we can still take advantage of synthesized implementations. Here we just extend that idea a bit by making the top-level key a property of the inner object type. Then the one type Envelope, or Wrapper, or whatever name you choose, can handle any content type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment