Preserve Clear Actions In Codable Updates
A person clears their nickname while offline. Your app saves the pending update, restores it on the next launch, and eventually sends it. The nickname is still there.
Somewhere along that trip, “clear this field” became “leave this field alone.” The nickname has acquired tenure.
The fix is to preserve the instruction, including through encoding and decoding. We’ll build a small update type for two nullable text fields, then apply a restored update without replacing untouched values.
This is established Codable behavior, checked here with Xcode 27.2 and Swift 6.4.2. The complete example targets iOS 17 and macOS 14. It complements our durable outbox by defining what an update means before the outbox stores it.
Give the endpoint an explicit contract
Suppose our profile endpoint defines these operations:
| Request body | Meaning for nickname |
|---|---|
{} | Leave the existing value alone |
{"nickname": null} | Clear the existing value |
{"nickname": "Sam"} | Replace the value with Sam |
{"nickname": ""} | Replace the value with an empty string |
The last two rows are both replacements. Whether the server allows an empty nickname is a separate validation rule. Don’t quietly turn empty text into a clear operation inside the codec.
Confirm these meanings with your service. The HTTP method PATCH alone doesn’t establish them. JSON Merge Patch, for example, gives null a removal meaning and defines additional rules for objects and arrays. Our example implements the agreed contract for two text fields; adapting a nested object needs its own rules.
An optional value loses one instruction
An ordinary optional property combines missing and explicit null into nil when decoded through synthesized Codable. That is intentional, as Codable designer Itai Ferber explains. It is convenient for many response models, but our update has three states to represent.
There are existing answers to both the general decodeIfPresent question and the specific problem of restoring saved requests. The extra work here is carrying that distinction all the way through a saved update and its application.
Use an enum so each instruction has a name. Place the Swift blocks below in one file, in order.
import Foundation
nonisolated enum TextChange: Equatable, Sendable {
case unchanged
case clear
case set(String)
func applying(to current: String?) -> String? {
switch self {
case .unchanged: current
case .clear: nil
case .set(let text): text
}
}
}
A profile’s stored nickname can still be String?. TextChange describes what to do to it. This also gives a form explicit choices: Clear produces .clear, editing text produces .set(text), and leaving the field untouched produces .unchanged.
The type-level nonisolated declarations keep these value types usable under an app’s MainActor-default isolation setting. They use the current compiler’s supported syntax. The codec itself is synchronous.
Ask the containing object whether a key exists
A missing key belongs to the object that contains it. A standalone value decoder can’t inspect a field that was never supplied.
We can express the three cases directly with contains(_:) and decodeNil(forKey:). Check presence first because decodeNil(forKey:) throws for a missing key.
extension TextChange {
nonisolated init<Key: CodingKey>(
from container: KeyedDecodingContainer<Key>,
forKey key: Key
) throws {
guard container.contains(key) else {
self = .unchanged
return
}
if try container.decodeNil(forKey: key) {
self = .clear
} else {
self = .set(try container.decode(String.self, forKey: key))
}
}
nonisolated func encode<Key: CodingKey>(
to container: inout KeyedEncodingContainer<Key>,
forKey key: Key
) throws {
switch self {
case .unchanged:
break
case .clear:
try container.encodeNil(forKey: key)
case .set(let text):
try container.encode(text, forKey: key)
}
}
}
The throwing string decode is deliberate. A number, Boolean, object, or array is malformed for this field and must reach the caller as an error. try? would risk converting a broken request into a valid-looking instruction.
For encoding, .unchanged makes no call for that key. .clear calls encodeNil(forKey:). Bart Jacobs’s Cocoacasts article on encoding null explains why synthesized optional encoding can omit a field you intended to clear. Here, the containing object explicitly controls omission as well as null.
Notice that TextChange has no Codable conformance. Its methods require a keyed container. That keeps the omission decision where the key exists and avoids inventing a standalone JSON representation for .unchanged.
A recent NativeFirst discussion also explores a three-state representation. Its wrapper composition exposes a useful failure case: decoding a null-aware value with decodeIfPresent(Wrapper.self, forKey:) still returns nil for JSON null before the wrapper’s initializer can handle it. Moving null handling into the value type doesn’t bypass the outer container’s behavior. The sample checks below reproduce that failure independently.
Make the update own its wire format
Now connect those operations to the endpoint’s two supported fields:
nonisolated struct ProfileUpdate: Codable, Equatable, Sendable {
var nickname: TextChange
var statusMessage: TextChange
enum CodingKeys: String, CodingKey {
case nickname, statusMessage
}
init(
nickname: TextChange = .unchanged,
statusMessage: TextChange = .unchanged
) {
self.nickname = nickname
self.statusMessage = statusMessage
}
init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
nickname = try TextChange(from: container, forKey: .nickname)
statusMessage = try TextChange(from: container, forKey: .statusMessage)
}
func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try nickname.encode(to: &container, forKey: .nickname)
try statusMessage.encode(to: &container, forKey: .statusMessage)
}
}
nonisolated struct Profile: Equatable, Sendable {
var nickname: String?
var statusMessage: String?
}
extension ProfileUpdate {
nonisolated func applying(to profile: Profile) -> Profile {
Profile(
nickname: nickname.applying(to: profile.nickname),
statusMessage: statusMessage.applying(to: profile.statusMessage)
)
}
}
Decode the entire update before applying it. If statusMessage has an invalid JSON type, decoding throws and no Profile has been mutated. The successful application returns a new value.
The defaults in the normal initializer help callers construct an update. The custom decoding initializer independently establishes missing-key behavior. A property default alone would not customize synthesized decoding.
This is an app-owned model for two known fields. Unknown keys are ignored by this implementation and won’t survive re-encoding. If you store updates across app versions, version the surrounding queue format and explicitly reject unsupported versions before decoding their payloads. Our Codable file-versioning article covers that boundary.
Restore intent, then apply it to the right record
Here’s an executable example. The encoded update clears nickname and omits statusMessage:
nonisolated func restoredProfileExample() throws -> Profile {
let pending = ProfileUpdate(nickname: .clear)
let saved = try JSONEncoder().encode(pending)
// An outbox can persist these bytes as its versioned payload.
let restored = try JSONDecoder().decode(ProfileUpdate.self, from: saved)
let current = Profile(
nickname: "Sam",
statusMessage: "Available after lunch"
)
return restored.applying(to: current)
}
The result has a nil nickname and the existing status message. If the current profile’s status message changed while this update was pending, applying .unchanged preserves that current value rather than restoring an old profile snapshot.
Keep the account, record identifier, schema version, and any server revision precondition in the outbox’s existing envelope. This small payload doesn’t decide which profile to modify. Its preservation rule also doesn’t resolve competing edits to the same field. An endpoint that requires a revision or If-Match still requires it.
For an outgoing request, pass the encoded update to the existing networking layer using the service’s documented content type. Retain the saved intent until the server acknowledges it. If delivery is uncertain, follow the endpoint’s retry contract; a correct JSON body doesn’t by itself make every request safe to repeat. See our retry article.
Test the JSON shape as well as the Swift value
A round-trip test alone can miss a symmetric mistake. An incorrect encoder and decoder might agree with each other while both disagree with the server.
Check the actual object too:
| Check | Expected result |
|---|---|
Encode .unchanged | The key is absent |
Encode .clear | The key exists with JSON null |
Encode .set("") | The key exists with an empty string |
Decode {} | Both fields are .unchanged |
| Decode a null field | That field is .clear |
Decode the string "null" | .set("null") |
| Decode a number, Boolean, object, or array field | Throw typeMismatch |
| Clear one field, omit the other | Preserve the other field’s current value |
| Save, reopen, and re-encode | Preserve each modeled instruction and its JSON shape |
Download the complete sample and checks. It includes every Swift block above, wire-shape assertions, malformed-input checks, and negative controls for optional synthesis and the null-aware-wrapper trap.
Verification: the exact Swift blocks compile with Swift 6 warnings treated as errors for iOS 17 and macOS 14 deployment targets. The checks run on macOS 27.2 and a native iOS 27.2 simulator app, under both ordinary and MainActor-default isolation. Separate writer and reader launches verify saved payloads. These checks establish the sample’s codec and application behavior; an actual server, delivery retry, and older-OS runtime behavior need their own integration tests.