Skip to content

Instantly share code, notes, and snippets.

@htinlinn
htinlinn / DecodableRoot.swift
Last active June 3, 2023 21:10
Decode JSON at root level based on a key
extension JSONDecoder {
func decode<T: Decodable>(_ type: T.Type, from data: Data, keyedBy key: String?) throws -> T {
if let key = key {
// Pass the top level key to the decoder.
userInfo[.jsonDecoderRootKeyName] = key
let root = try decode(DecodableRoot<T>.self, from: data)
return root.value
} else {