# \[Pitch\] JSONDecoder.nullDecodingStrategy

**URL:** <https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980>\
**Category:** Pitches\
**Tags:** codable, json, optional\
**Created:** [June 25, 2018, 8:17pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980 "2018-06-25T20:17:11Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dan\_Stenmark](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dan_stenmark/32/1589_2.png) [@Dan\_Stenmark](https://forums.swift.org/u/Dan_Stenmark)\
**Post date:** [June 25, 2018, 8:17pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/1 "2018-06-25T20:17:11Z")

</div>

JSONDecoder currently does not differentiate between a payload containing an explicit `null` or the field being omitted. I would like to propose an additive change to include a decoding strategy for these situations:

```
class JSONDecoder {
    ...

    enum NullDecodingStrategy {
	    // Default, today's behavior
	    case implicit

	    // If struct contains "var anInt: Int?", valid JSON payloads must explicitly contain either {'anInt': <integer>} or {'anInt': null}. Not containing 'anInt' results in a decoding error.
	    // If struct contains "var anInt: Int??", {'anInt': <integer>} decodes as .some(.some(<integer>)), {'anInt': null} decodes as .some(.none), and the field being omitted results decodes as .none.
	    case explicit
    }

    var nullDecodingStrategy: NullDecodingStrategy = . implicit

    ...
}

```

**_(DISCLAIMER: Might need some bikeshedding.)_**

---

<div class="post-metadata">

**Author:** ![itaiferber](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/itaiferber/32/33840_2.png) [@itaiferber](https://forums.swift.org/u/itaiferber)\
**Post date:** [June 25, 2018, 8:29pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/2 "2018-06-25T20:29:59Z")

</div>

`JSONDecoder` does actually differentiate between these cases — you can distinguish by calling `decode(Int?.self, forKey: ...)` (which necessitates that the field be present, but the value may be `null`) vs. `decodeIfPresent(Int.self, forKey: ...)` (which allows either the field to be omitted, or the value to be `null`):

```swift
import Foundation

struct Foo : Decodable {
    let a: Int?
    let b: Int?
    
    private enum CodingKeys: String, CodingKey {
        case a, b
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        a = try container.decode(Int?.self, forKey: .a)
        b = try container.decodeIfPresent(Int.self, forKey: .b)
    }
}

let payloads = [
    // Succeeds
    """
    {"a": 5, "b": 10}
    """.data(using: .utf8)!,
    
    // Succeeds
    """
    {"a": null, "b": 10}
    """.data(using: .utf8)!,
    
    // Fails, "a" may not be missing
    """
    {"b": 10}
    """.data(using: .utf8)!,
    
    // Succeeds
    """
    {"a": 5, "b": null}
    """.data(using: .utf8)!,
    
    // Succeeds
    """
    {"a": 5}
    """.data(using: .utf8)!
]

let decoder = JSONDecoder()
for payload in payloads {
    do {
        let foo = try decoder.decode(Foo.self, from: payload)
        print(foo)
    } catch {
        print("Failed to parse '\(String(data: payload, encoding: .utf8)!)': \(error)")
    }
}

```

One thing to keep in mind when using synthesized conformances is that optional values get `decodeIfPresent(...)` called for them, rather than `decode(...)`, to be more permissive.

* * *

This isn't unique to `JSONDecoder`, BTW, but a requirement of the `KeyedDecodingContainer` protocol:

- [`decodeIfPresent<T>(_:forKey:)`](https://developer.apple.com/documentation/swift/keyeddecodingcontainer/2894339-decodeifpresent)
- [`decode<T>(_:forKey:)`](https://developer.apple.com/documentation/swift/keyeddecodingcontainer/2921358-decode)
- [`contains(_:)`](https://developer.apple.com/documentation/swift/keyeddecodingcontainer/2893337-contains) (which helps distinguish between what would happen here, without decoding)

Is there a use case you have in mind which this does not cover?

---

<div class="post-metadata">

**Author:** ![Dan\_Stenmark](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dan_stenmark/32/1589_2.png) [@Dan\_Stenmark](https://forums.swift.org/u/Dan_Stenmark)\
**Post date:** [June 25, 2018, 9:00pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/3 "2018-06-25T21:00:35Z")

</div>

The problem with the Foo example above is that it still obfuscates from any consumer of Foo whether the value is present or nil, which is more aptly represented via nested Optionals (e.g. Optional\<Optional\>). While it's true the support can be implemented manually with additional legwork, the goal of NullDecodingStrategy is to streamline this + enable synthesized conformances to provide this for free. This is especially useful for data querying languages (such as GraphQL) that make a strong semantic distinction between a field in a returned payload being null and it being omitted altogether.

This would ideally look like:

```
struct Foo: Codable {
    var a: Int
    var b: Int?
    var c: Int??
}

let payloads = [
    // Succeeds, (a: 5, b: .some(10), c: .some(.some(15)))
    """
    {"a": 5, "b": 10, "c": 15}
    """.data(using: .utf8)!,

    // Succeeds, (a: 5, b: .some(10), c: .some(.none))
    """
    {"a": 5, "b": 10, "c": null}
    """.data(using: .utf8)!,

    // Succeeds, (a: 5, b: .some(10), c: .none)
    """
    {"a": 5, "b": 10}
    """.data(using: .utf8)!,

    // Succeeds, (a: 5, b: .none, c: .none)
    """
    {"a": 5, "b": null}
    """.data(using: .utf8)!,

    // Fails, "a" cannot be null
    """
    {"a": null, "b": 10, "c": 15}
    """.data(using: .utf8)!,

    // Fails, "a" may not be missing
    """
    {"b": 10}
    """.data(using: .utf8)!,

    // Fails, "b" may not be missing
    """
    {"a": 5}
    """.data(using: .utf8)!
]

let decoder = JSONDecoder()
decoder.nullDecodingStrategy = .explicit

for payload in payloads {
    do {
        let foo = try decoder.decode(Foo.self, from: payload)
        print(foo)
    } catch {
        print("Failed to parse '\(String(data: payload, encoding: .utf8)!)': \(error)")
    }
}

```

---

<div class="post-metadata">

**Author:** ![itaiferber](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/itaiferber/32/33840_2.png) [@itaiferber](https://forums.swift.org/u/itaiferber)\
**Post date:** [June 25, 2018, 9:52pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/4 "2018-06-25T21:52:32Z")

</div>

Having not worked with GraphQL directly, please enlighten me — in what use cases is it important for a consumer of `Foo` to know whether one of its fields was missing vs. null?

My concern about distinguishing between `Optional` and `Optional<Optional>` is multi-fold:

1. The current behavior for handling of optionals falls out very nicely from a very simple implementation on `Optional` that follows from general rules: encoding an `Optional<T>` encodes the inner `T` if it is present, regardless of what `T` is — it could be a type like `Int` (in so, unwrapping `Int? → Int`), or it could be an optional itself. Encoding an `Int??` encodes an `Int?`, which encodes an `Int`; the rule for the `Optional` itself is very simple. (Decoding is similar here — decoding an `Int??` decodes an `Int?` which decodes an `Int`, wrapping the values as we unwind.)

2. Giving preferential treatment to such a type also raises more questions — what does `Int???` then imply? `Int????` (i.e. what makes `Optionalⁿ<T>` special for `n == 2`?)

3. It's not always valid to read into the type annotation in this way. Consider the following:

Given this, and the fact that `T??` types can be difficult to consume correctly (if you're not careful about how you unwrap, you could end up throwing away information; this is just my personal opinion, though), would it not be nicer to work with a field type other than `Optional<Optional<T>>` which does actually semantically indicate the difference between the field being missing and the value being null? (You would lose automatic synthesis, yes, but you can add extensions to the container protocols that make it really easy to decode a `Field<T>` [where `Field` can be an `enum` that strongly distinguishes between `.none` and `.missing`].)

---

<div class="post-metadata">

**Author:** ![leisurehound](https://avatars.discourse-cdn.com/v4/letter/l/50afbb/32.png) [@leisurehound](https://forums.swift.org/u/leisurehound)\
**Post date:** [November 7, 2024, 5:49pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/5 "2024-11-07T17:49:38Z")

</div>

I know this is old, but FWIW I'm currently consuming a feed where the publisher has documented that a key not being present is semantically different than where the key is present but the value is null, and I need to respond accordingly to those semantic differences.

Is creating my own keys and decoding field by field with all the boilerplate that @itaiferber proposes above still the only viable approach to manage this?

---

<div class="post-metadata">

**Author:** ![phoneyDev](https://avatars.discourse-cdn.com/v4/letter/p/49beb7/32.png) [@phoneyDev](https://forums.swift.org/u/phoneyDev)\
**Post date:** [November 8, 2024, 10:05pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/6 "2024-11-08T22:05:08Z")

</div>

That will work. You might also encapsulate the same logic inside a `propertywrapper` and apply that to your property.

---

<div class="post-metadata">

**Author:** ![itaiferber](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/itaiferber/32/33840_2.png) [@itaiferber](https://forums.swift.org/u/itaiferber)\
**Post date:** [November 8, 2024, 11:18pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/7 "2024-11-08T23:18:13Z")

</div>

> [@leisurehound](#):
>
> Is creating my own keys and decoding field by field with all the boilerplate that @itaiferber proposes above still the only viable approach to manage this?

Implementing `init(from:)` yourself is currently the only way to handle this, since neither `decode(_:forKey:)` nor `decodeIfPresent(_:forKey:)` will do what you want:

1. `decode(_:forKey:)` will throw an error if the key is missing
2. `decodeIfPresent(_:forKey:)` won't distinguish between a missing key and a `null` value

Distinguishing between non-existent key and a `null` value requires using `contains(_:)`, and you'd need to decide how to handle the result. This, for example, is one way to represent the data (but not the only way):

```swift
struct S: Decodable {
    // Double-Optional:
    // * Outer layer indicates key missing vs. present
    // * Inner layer indicates value `null` vs. present
    var x: Int??

    init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if container.contains(.x) {
            x = container.decode(Int?.self, forKey: .x)
        } else {
            x = nil
        }
    }
}

```

> [@leisurehound](#):
>
> creating my own keys

FWIW, if your type is `Encodable` too, you could leverage the fact that letting the compiler synthesize `Encodable` conformance will generate the keys for you, and then use those keys in your `init(from:)`.

* * *

> [@phoneyDev](#):
>
> You might also encapsulate the same logic inside a `propertywrapper` and apply that to your property.

Unfortunately, you can't handle this with a property wrapper because of how property wrappers are represented under the hood, and how they interact with compiler synthesis.

A type like

```swift
struct S {
    @MyPropertyWrapper var x: Int?
}

```

generates code that looks approximately like

```swift
struct S {
    private var _x: MyPropertyWrapper<Int?>
    var x: Int? {
        get { _x.wrappedValue }
        set { _x.wrappedValue = newValue }
    }
}

```

This produces an `init(from:)` that looks like

```swift
init(from decoder: any Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    _x = try container.decode(MyPropertyWrapper<Int?>.self, forKey: .x)
}

```

Because of how the synthesized code is structured, an error would get thrown on a missing key before the property wrapper code would ever get called, one level deeper.

(A bit more info on this in [Cleaner Way to Decode Missing JSON Keys? - #7 by itaiferber](https://forums.swift.org/t/cleaner-way-to-decode-missing-json-keys/40523/7) and [[Pitch] Nullable and Non-Optional Nullable Types - #17 by itaiferber](https://forums.swift.org/t/pitch-nullable-and-non-optional-nullable-types/63952/17))

* * *

There's also quite a bit of prior discussion in threads like

- [Decoding of optionals missing in json](https://forums.swift.org/t/decoding-of-optionals-missing-in-json/52475)
- [Optional decoding superpowers](https://forums.swift.org/t/optional-decoding-superpowers/63649)

---

<div class="post-metadata">

**Author:** ![leisurehound](https://avatars.discourse-cdn.com/v4/letter/l/50afbb/32.png) [@leisurehound](https://forums.swift.org/u/leisurehound)\
**Post date:** [November 10, 2024, 3:48am UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/8 "2024-11-10T03:48:37Z")

</div>

> [@itaiferber](#):
>
> Implementing `init(from:)` yourself is currently the only way to handle this, since neither `decode(_:forKey:)` nor `decodeIfPresent(_:forKey:)` will do what you want:
> 
> 1. `decode(_:forKey:)` will throw an error if the key is missing
> 2. `decodeIfPresent(_:forKey:)` won't distinguish between a missing key and a `null` value
> 
> Distinguishing between non-existent key and a `null` value requires using `contains(_:)`, and you'd need to decide how to handle the result. This, for example, is one way to represent the data (but not the only way):
> 
> ```swift
> struct S: Decodable {
> // Double-Optional:
> // * Outer layer indicates key missing vs. present
> // * Inner layer indicates value `null` vs. present
> var x: Int??
> 
> init(from decoder: any Decoder) throws {
> let container = try decoder.container(keyedBy: CodingKeys.self)
> if container.contains(.x) {
> x = container.decode(Int?.self, forKey: .x)
> } else {
> x = nil
> }
> }
> }
> 
> ```
> 
> > [@leisurehound](#):
> >
> > creating my own keys
> 
> FWIW, if your type is `Encodable` too, you could leverage the fact that letting the compiler synthesize `Encodable` conformance will generate the keys for you, and then use those keys in your `init(from:)`.

Thanks. I'll give that a go and reach back if either results of questions. Appreciate your help.

---

<div class="post-metadata">

**Author:** ![vns](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vns/32/37396_2.png) [@vns](https://forums.swift.org/u/vns)\
**Post date:** [November 10, 2024, 9:29am UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/9 "2024-11-10T09:29:40Z")

</div>

> [@itaiferber](#):
>
> Because of how the synthesized code is structured, an error would get thrown on a missing key before the property wrapper code would ever get called, one level deeper.

Yeah, one need to use explicit custom wrapper type instead of a property wrapper to generalize this:

```swift
let value: ExplicitNullCodable<Int>?

```

Then in case of a missing field, `value` itself would be `nil`. And the wrapper type can be

```swift
struct ExplicitNullCodable<Value>: Codable where Value: Codable {
    let value: Value?

    init(from decoder: any Decoder) {
        // implement on your own 
    }
}

```

Then it would more likely need a bunch of conformances to “expressible by literal” to use it conveniently.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [November 11, 2024, 10:58pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/10 "2024-11-11T22:58:58Z")

</div>

I think this is the thing to look at first:

```swift
[1, 2, nil, 4]

```

Convert this to json? Easy, it could be modelled with `[Int?]`.

Now, what about this one:

```swift
[1, 2, nil, "4"]

```

🤔

How about:

```swift
enum Value: Equatable {
    case int(Int)
    case string(String)
    case null
}

struct Null {}

```

> **With some obvious boilerplate**
>
> ```swift
> extension Value: Codable {
> func encode(to encoder: Encoder) throws {
> var container = encoder.singleValueContainer()
> switch self {
> case .int(let v): try container.encode(v)
> case .string(let v): try container.encode(v)
> case .null: try container.encode(Null())
> }
> }
>     
> init(from decoder: Decoder) throws {
> let container = try decoder.singleValueContainer()
> if let v = try? container.decode(Int.self) {
> self = .int(v)
> } else if let v = try? container.decode(String.self) {
> self = .string(v)
> } else if container.decodeNil() {
> self = .null
> } else {
> fatalError("TODO")
> }
> }
> }
> 
> extension Null: Codable {
> func encode(to encoder: Encoder) throws {
> var container = encoder.singleValueContainer()
> try container.encodeNil()
> }
> init(from decoder: Decoder) throws {
> fatalError("unused")
> }
> }
> 
> ```

Test app:

```swift
var items: [Value] = [.int(1), .int(2), .null, .string("4")]
let data = try! JSONEncoder().encode(items)
let s = String(data: data, encoding: .utf8)!

```

outputs:

> [1, 2, null, "4"]

and back:

```swift
let items2 = try! JSONDecoder().decode([Value].self, from: data)
print(items2)
precondition(items == items2) // ok

```

This way looks more straightforward / obvious than playing tricks with "??"

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [November 14, 2024, 8:54am UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/11 "2024-11-14T08:54:23Z")

</div>

Another take:

```swift
struct S: Codable, Equatable {
    let one: Int
    let two: String
    let three: MyOptional<Int>
    let four: MyOptional<Int>
}

```

Encoding this into JSON gives:

```swift
{"one":1,"three":null,"two":"2","four":4}

```

> **MyOptional type (quite small)**
>
> ```swift
> enum MyOptional<Wrapped: Codable & Equatable>: Codable & Equatable, ExpressibleByNilLiteral {
> init(nilLiteral: Void) { self = .none }
> case none, some(Wrapped)
> init(from decoder: Decoder) throws {
> let container = try decoder.singleValueContainer()
> if container.decodeNil() {
> self = .none
> } else {
> self = .some(try container.decode(Wrapped.self))
> }
> }
> func encode(to encoder: Encoder) throws {
> var container = encoder.singleValueContainer()
> switch self {
> case .none: try container.encodeNil()
> case .some(let wrapped): try container.encode(wrapped)
> }
> }
> }
> 
> ```

> **Test app**
>
> ```swift
> var value = S(one: 1, two: "2", three: nil, four: .some(4))
> let encoder = JSONEncoder()
> let data = try! encoder.encode(value)
> let s = String(data: data, encoding: .utf8)!
> let value2 = try! JSONDecoder().decode(S.self, from: data)
> precondition(value == value2)
> print(s)
> 
> ```

——————

Edit: this fails to decode json with absent key:

```swift
{"one":1,"two":"2","four":4}

```

🙁

---

<div class="post-metadata">

**Author:** ![swhitty](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/swhitty/32/10082_2.png) [@swhitty](https://forums.swift.org/u/swhitty)\
**Post date:** [November 15, 2024, 7:04pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/12 "2024-11-15T19:04:27Z")

</div>

> [@tera](#):
>
> this fails to decode json with absent key:

An extension on `KeyedDecodingContainer` is required to decode wrapped or custom optional types.

I use [this property wrapper technique](https://forums.swift.org/t/propertywrapper-decoding-behaviour/61076/2).

---

<div class="post-metadata">

**Author:** ![itaiferber](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/itaiferber/32/33840_2.png) [@itaiferber](https://forums.swift.org/u/itaiferber)\
**Post date:** [November 15, 2024, 8:02pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/13 "2024-11-15T20:02:11Z")

</div>

> [@tera](#):
>
> Edit: this fails to decode json with absent key:
> 
> `{"one":1,"two":"2","four":4}`

Yes, for the same reason above: compiler synthesis only generates `decodeIfPresent()` calls for `Optional`. We've, er, [had this discussion before](https://forums.swift.org/t/optional-decoding-superpowers/63649), [on more than one occasion](https://forums.swift.org/t/decoding-of-optionals-missing-in-json/52475) 😅

* * *

> [@swhitty](#):
>
> An extension on `KeyedDecodingContainer` is required to decode wrapped or custom optional types.

Although this works, it's _very_ important to understand why and how it works, and take into account that this is a _very_ fragile solution that is hard to recommend.

An extension to `KeyedDecodingContainer` only works because:

1. `Codable` compiler synthesis currently manipulates the AST directly, generating code _as-if_ you had written the source code yourself; because of this, actual resolution of method overloads allows type checking to select more specific overloads for specific calls (e.g., those found in extensions)
2. An extension in your module makes that overload available for the compiler to select _within_ your module (and modules you make it visible to)

It's _really_ important to keep in mind that **this does not actually change the _behavior_ of `KeyedDecodingContainer` at all** , just that it monkey-patches a new overload of the method with the same name that makes it visible at synthesis time. This means that:

1. Modules which don't have this extension at compile-time will **silently** behave differently from ones that do. This can happen when, e.g.,
  - Module `A` declares an `internal` extension, and Module `B` encodes and decodes the same type
  - Module `A` declares a `public` extension, but Module `B` is compiled before it and encodes and decodes the same type

2. You can accidentally and silently end up in situation (1) by moving types/extensions between sibling modules
3. You can't override behavior for modules you don't control
4. If other modules also define a similar extension, their version will win out over yours when they compile
5. If compiler synthesis changes (e.g., it starts performing `Codable` method lookup only in the stdlib), this is liable to silently break

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [November 15, 2024, 9:05pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/14 "2024-11-15T21:05:22Z")

</div>

> [@itaiferber](#):
>
> Yes, for the same reason above: compiler synthesis only generates `decodeIfPresent()` calls for `Optional`. We've, er, [had this discussion before](https://forums.swift.org/t/optional-decoding-superpowers/63649), [on more than one occasion](https://forums.swift.org/t/decoding-of-optionals-missing-in-json/52475) 😅

I know, yet it is surprising me every time! 🤣

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [November 15, 2024, 9:18pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/15 "2024-11-15T21:18:18Z")

</div>

> [@itaiferber](#):
>
> An extension to `KeyedDecodingContainer` only works because

The warning about its limited usage noted, but I could see bits and pieces every here and there but not a standalone working out of the box sample. Could anyone show me the whole thing? And does it work only with the keyed containers, not with singleValueContainer I am trying to use above?

---

<div class="post-metadata">

**Author:** ![itaiferber](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/itaiferber/32/33840_2.png) [@itaiferber](https://forums.swift.org/u/itaiferber)\
**Post date:** [November 15, 2024, 9:32pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/16 "2024-11-15T21:32:58Z")

</div>

There really isn't very much to this trick (so you've probably already seen all of it). Let's say you've got a type that looks like

```swift
struct S {
    static func foo<T>(_ t: T) {
        print("S.foo<\(T.self)>(\(t))")
    }
}

```

You can call it like so:

```swift
S.foo(42) // => S.foo<Int>(42)

struct MyType {}
S.foo(MyType()) // => S.foo<MyType>(MyType())

```

If you define an extension that overloads `foo` for your custom type,

```swift
extension S {
    static func foo(_ mt: MyType) {
        print("Custom S.foo<MyType>(\(mt))")
    }
}

```

then you get

```swift
S.foo(42) // => S.foo<Int>(42)
S.foo(MyType()) // => Custom S.foo<MyType>(MyType())

```

At the _callsite_ of `S.foo(MyType())`, the compiler gets to choose between `S.foo<T>(_: T)` and `S.foo(_: MyType)`, and it selects the more specific option when it can.

* * *

The principle is the same: if you define

```swift
extension KeyedDecodingContainer {
    func decode(_ t: MyType.Type, forKey key: Key) -> MyType {
        // ...
    }
}

```

then

```swift
init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    myVal = try container.decode(MyType.self, forKey: .myVal)
}

```

will call the more specific `KeyedDecodingContainer.decode(_: MyType.Type, forKey: Key)` instead of the generic one.

The "trick" is that `Codable` synthesis will output code as if you had written the above directly in a source file, so the compiler has the _opportunity_ to select between the overloads; if it happened at a later stage in compilation, this wouldn't work.

> [@tera](#):
>
> And does it work only with the keyed containers, not with singleValueContainer I am trying to use above?

This works with all types.

If you add an extension to `singleValueContainer` and call it from the same module, it will get picked up. The compiler only ever synthesizes code using keyed containers, though, so this would only be relevant to custom `init(from:)` implementations in your code which you call directly.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [November 15, 2024, 10:06pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/17 "2024-11-15T22:06:41Z")

</div>

Thank you, what you write makes sense... But `KeyedDecodingContainer` is a struct while `SingleValueContainer` is a protocol, is that what prohibits me using this approach?

```swift
enum MyType: Codable { case none, some }

struct S1: Codable {
    var a = 0
    var b: MyType = .some
}

typealias S2 = [MyType]

extension KeyedDecodingContainer {
    func decode(_ t: MyType.Type, forKey key: Key) -> MyType {
        self.contains(key) ? .some : .none
    }
}
extension SingleValueDecodingContainer {
    func decode(_ type: MyType.Type) throws -> MyType {
        fatalError("never here") // not hitting this 🛑
    }
}
let data1 = "{\"a\":1, \"b\":2}".data(using: .utf8)!
let value1 = try! JSONDecoder().decode(S1.self, from: data1) // ✅
print(value1)

let data2 = "[42]".data(using: .utf8)!
let value2 = try! JSONDecoder().decode(S2.self, from: data2) // 🛑 runtime trap
print(value2)

```

---

<div class="post-metadata">

**Author:** ![itaiferber](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/itaiferber/32/33840_2.png) [@itaiferber](https://forums.swift.org/u/itaiferber)\
**Post date:** [November 15, 2024, 11:02pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/18 "2024-11-15T23:02:26Z")

</div>

No, you're hitting a few unrelated issues here:

1. Because `MyType` doesn't conform to `RawRepresentable` with a `RawValue` of one of the `Codable` primitives, it gets synthesized conformance, and [synthesized conformance for enums](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0295-codable-synthesis-for-enums-with-associated-values.md) produces dictionaries.

2. Even if you give `MyType` a `RawValue` (e.g., `enum MyType: Int, Codable { ... }`) which will allow it to decode as an `Int`, neither `JSONDecoder().decode(MyType.self, from: ...)` nor `JSONDecoder().decode([MyType].self, from: ...)` will actually end up hitting your extension, because:

Here's an example that does hit this code path:

```swift
import Foundation

enum MyType: Int, Codable {
    case none, some
}

struct S: Decodable {
    let t: MyType

    init(from decoder: any Decoder) throws {
        let container = try decoder.singleValueContainer()
        t = try container.decode(MyType.self)
    }
}

// Comment this in or out to see the change in behavior.
/*
enum MyError: Error {
    case err
}

extension SingleValueDecodingContainer {
    func decode(_: MyType.Type) throws -> MyType {
        throw MyError.err
    }
}
*/

let json = "1".data(using: .utf8)!
do {
    let value = try JSONDecoder().decode(S.self, from: json)
    print(value) // without extension => S(t: MyType.some)
} catch {
    print(error) // with extension => err
}

```

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [November 15, 2024, 11:22pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/19 "2024-11-15T23:22:15Z")

</div>

Nice!

Although it looks like I'm still back to what we've discussed a few times before: Optional has superpowers that I can't simulate:

```swift
import Foundation

enum MyOptional: Codable { case none, some, someOther }

struct MyOptionalDoublyWrapped: Codable {
    let t: MyOptional
    init(_ t: MyOptional) { self.t = t }
    init(from decoder: any Decoder) throws {
        let container = try decoder.singleValueContainer()
        t = try container.decode(MyOptional.self)
    }
    func encode(to encoder: Encoder) throws {
        fatalError("TODO")
    }
}

```

```swift
struct SomethingReal: Codable {
    var x = 0
    var y: MyOptionalDoublyWrapped = .init(.some)
}

extension SingleValueDecodingContainer {
    func decode(_: MyOptional.Type) throws -> MyOptional {
        if decodeNil() {
            return .none
        } else if (try? decode(Int.self)) != nil {
            return .some
        } else {
            return .someOther
        }
    }
}

```

```swift
let data1 = ###"{"x":1, "y":42}"###.data(using: .utf8)!
let value1 = try JSONDecoder().decode(SomethingReal.self, from: data1)
print(value1) // ✅ .some

let data2 = ###"{"x":1, "y":null}"###.data(using: .utf8)!
let value2 = try JSONDecoder().decode(SomethingReal.self, from: data2)
print(value2) // ✅ .none

let data3 = ###"{"x":1}"###.data(using: .utf8)! 
let value3 = try JSONDecoder().decode(SomethingReal.self, from: data3)
// 🛑"No value associated with key CodingKeys(stringValue: \"y\"
print(value3)

```

---

<div class="post-metadata">

**Author:** ![leisurehound](https://avatars.discourse-cdn.com/v4/letter/l/50afbb/32.png) [@leisurehound](https://forums.swift.org/u/leisurehound)\
**Post date:** [August 16, 2025, 7:58pm UTC](https://forums.swift.org/t/pitch-jsondecoder-nulldecodingstrategy/13980/20 "2025-08-16T19:58:38Z")

</div>

Realize it’s been awhile, but have finally had to stop avoiding this feed’s inference of resetting on null vs being an optional when not present. This is what ChatGPT was able to get after series of prompts.

````swift
import Foundation

// MARK: - Core Enum

/// A three-state wrapper type that represents a value that can be present, absent, or explicitly reset.
/// 
/// - `.some(Wrapped)` contains a value.
/// - `.none` represents absence of a value (like `nil`).
/// - `.reset` explicitly indicates a value should be reset or cleared.
/// 
/// Example:
/// ```swift
/// var value: Resettable<Int> = .some(42)
/// value = .none
/// value = .reset
/// ```
enum Resettable<Wrapped> {
    case some(Wrapped)
    case none
    case reset
}

// MARK: - Optional-like Extensions

extension Resettable {
    
    /// Returns the wrapped value if `.some`, otherwise `nil`.
    ///
    /// Example:
    /// ```swift
    /// let x: Resettable<Int> = .some(5)
    /// print(x.value) // Optional(5)
    /// let y: Resettable<Int> = .none
    /// print(y.value) // nil
    /// ```
    var value: Wrapped? {
        if case let .some(v) = self { return v }
        return nil
    }

    /// Returns true if the value is `.some`.
    var isSome: Bool { if case .some = self { return true }; return false }
    
    /// Returns true if the value is `.none`.
    var isNone: Bool { if case .none = self { return true }; return false }
    
    /// Returns true if the value is `.reset`.
    var isReset: Bool { if case .reset = self { return true }; return false }

    /// Maps a `Resettable` value to another `Resettable` using the provided closure.
    ///
    /// Example:
    /// ```swift
    /// let x: Resettable<Int> = .some(2)
    /// let y = x.map { $0 * 3 } // .some(6)
    /// ```
    func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> Resettable<U> {
        switch self {
        case .some(let x): return .some(try transform(x))
        case .none: return .none
        case .reset: return .reset
        }
    }

    /// Maps a `Resettable` value to another `Resettable` with a closure that returns `Resettable`.
    ///
    /// Example:
    /// ```swift
    /// let x: Resettable<Int> = .some(2)
    /// let y = x.flatMap { $0 > 0 ? .some($0 * 2) : .none } // .some(4)
    /// ```
    func flatMap<U>(_ transform: (Wrapped) throws -> Resettable<U>) rethrows -> Resettable<U> {
        switch self {
        case .some(let x): return try transform(x)
        case .none: return .none
        case .reset: return .reset
        }
    }
}

// Optional-like coalescing
/// Provides a default value if the `Resettable` is `.none`. `.reset` propagates as `.reset`.
///
/// Example:
/// ```swift
/// let x: Resettable<Int> = .none
/// let y = x ?? 10 // .some(10)
/// let r: Resettable<Int> = .reset
/// let z = r ?? 5 // .reset
/// ```
func ??<T>(lhs: Resettable<T>, rhs: @autoclosure () -> T) -> Resettable<T> {
    switch lhs {
    case .some: return lhs
    case .none: return .some(rhs())
    case .reset: return .reset
    }
}

// MARK: - Literal Conformances

extension Resettable: ExpressibleByNilLiteral {
    /// Initializes a `.none` value.
    init(nilLiteral: ()) { self = .none }
}

extension Resettable: ExpressibleByIntegerLiteral where Wrapped == Int {
    /// Initializes a `.some` with an integer literal.
    init(integerLiteral value: Int) { self = .some(value) }
}

// MARK: - Equatable / Hashable

extension Resettable: Equatable where Wrapped: Equatable {
    /// Compares two `Resettable` values.
    ///
    /// Example:
    /// ```swift
    /// Resettable.some(1) == Resettable.some(1) // true
    /// Resettable.none == Resettable.none // true
    /// Resettable.reset == Resettable.reset // true
    /// ```
    static func == (lhs: Resettable<Wrapped>, rhs: Resettable<Wrapped>) -> Bool {
        switch (lhs, rhs) {
        case (.some(let a), .some(let b)): return a == b
        case (.none, .none): return true
        case (.reset, .reset): return true
        default: return false
        }
    }
}

extension Resettable: Hashable where Wrapped: Hashable {
    func hash(into hasher: inout Hasher) {
        switch self {
        case .some(let value): hasher.combine(0); hasher.combine(value)
        case .none: hasher.combine(1)
        case .reset: hasher.combine(2)
        }
    }
}

// MARK: - Printing

extension Resettable: CustomStringConvertible, CustomDebugStringConvertible {
    var description: String {
        switch self {
        case .some(let value): return String(describing: value)
        case .none: return "nil"
        case .reset: return "reset"
        }
    }

    var debugDescription: String {
        switch self {
        case .some(let value): return "Resettable.some(\(String(reflecting: value)))"
        case .none: return "Resettable.none"
        case .reset: return "Resettable.reset"
        }
    }
}

// MARK: - Codable

extension Resettable: Codable where Wrapped: Codable {
    /// Encodes `.some` as the wrapped value, `.none` is omitted, `.reset` encoded as `nil`.
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .some(let value): try container.encode(value)
        case .none: break
        case .reset: try container.encodeNil()
        }
    }

    /// Decodes a value. `nil` → `.reset`, missing → `.none`, otherwise `.some`.
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if container.decodeNil() {
            self = .reset
        } else if let value = try? container.decode(Wrapped.self) {
            self = .some(value)
        } else {
            self = .none
        }
    }
}

// MARK: - Property Wrapper

@propertyWrapper
struct ResettableCodable<Value: Codable>: Codable {
    var wrappedValue: Resettable<Value>

    init(wrappedValue: Resettable<Value>) {
        self.wrappedValue = wrappedValue
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if container.decodeNil() {
            self.wrappedValue = .reset
        } else if let value = try? container.decode(Value.self) {
            self.wrappedValue = .some(value)
        } else {
            self.wrappedValue = .none
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch wrappedValue {
        case .some(let value): try container.encode(value)
        case .none: break
        case .reset: try container.encodeNil()
        }
    }
}

// MARK: - Dynamic Member Lookup for Optional-like Chaining

@dynamicMemberLookup
struct ResettableWrapper<Wrapped> {
    let resettable: Resettable<Wrapped>

    /// Dynamically access properties of the wrapped type if `.some`.
    ///
    /// Example:
    /// ```swift
    /// struct Info { let name: String }
    /// let r: Resettable<Info> = .some(Info(name: "Tim"))
    /// print(r.opt.name) // Optional("Tim")
    /// ```
    subscript<T>(dynamicMember keyPath: KeyPath<Wrapped, T>) -> T? {
        guard case let .some(value) = resettable else { return nil }
        return value[keyPath: keyPath]
    }
}

extension Resettable {
    var opt: ResettableWrapper<Wrapped> { ResettableWrapper(resettable: self) }
}

// MARK: - Proxy-based Postfix Operator

@dynamicMemberLookup
struct ResettableProxy<Wrapped> {
    fileprivate let wrapped: Wrapped?

    init(_ wrapped: Wrapped?) {
        self.wrapped = wrapped
    }

    /// Dynamically access properties of the wrapped type
    ///
    /// Example:
    /// ```swift
    /// let info: Resettable<Info> = .some(Info(name: "Tim"))
    /// if let name = info~.name { print(name) }
    /// ```
    subscript<T>(dynamicMember keyPath: KeyPath<Wrapped, T>) -> T? {
        wrapped?[keyPath: keyPath]
    }

    /// Returns the underlying wrapped value if present.
    var value: Wrapped? { wrapped }
}

postfix operator ~
/// Returns a `ResettableProxy` for optional chaining and dynamic member lookup
///
/// Example:
/// ```swift
/// let info: Resettable<Info> = .some(Info(name: "Tim"))
/// if let name = info~.name { print(name) }
/// ```
postfix func ~<T>(resettable: Resettable<T>) -> ResettableProxy<T> {
    switch resettable {
    case .some(let v): return ResettableProxy(v)
    default: return ResettableProxy(nil)
    }
}

```

````

Accessing the value of a resettable is not as clean as redefining another symbol to act like ? for an optional, but the areas that need this is limited so should be ok. Curious if others feel this is reasonable. I did have some of this envisioned as I started, but the AI rounded it out to make it a bit nicer as the consumer of a Resettable.
