A Codable Undefinable type for handling JSON undefined values.

Overview

Undefinable

Overview

The purpose of this type is represent the JSON undefined state in Swift structs and classes.

The Undefinable enum is a generic with a Wrapped type, similar to Optional. The value is one of:

  • .undefined
  • .defined(Wrapped?)

When encoded with a KeyedEncodingContainer, an .undefined value will cause the entire key to be excluded from the encoded result.

When decoded with a KeyedDecodingContainer, an missing key will be decoded into an .undefined value.

null JSON values translate to .defined(nil)

Example

The best way to explain the user of Undefined is to demonstrate potential uses.

For example, consider the following simple struct:

struct User {
    var name: String
}

Now imagine in a framework like Vapor, you create a PATCH route which takes in a request like this:

struct UserUpdateRequest: Content {
    var name: String?
}

So it's easy to allow the PATCH request to optionally update the name by doing something like:

if let name = request.name {
    user.name = name
}

Now what happens when we want to add an optional age to our User struct?

struct User {
    var name: String
    var age: Int? // The user can optionally provide their age.
}

So adding an optional age to the PATCH request will not work as we won't know if it is nil because there was no change, or if it is nil because the user wants to explicitly set the age to nil. This is where we can use Undefinable.

struct UserUpdateRequest: Content {
    var name: String?
    var age: Undefinable<Int>
}

Now in our controller, we can do this:

    request.age.unwrap {
        user.age = $0
    }
}

If there was no JSON key in the request for age, the value would be .undefined and the closure for unwrap would not be executed. However if the key existed and was set to either a value or null, the closure would execute and $0 would be an Optional<Int>.

For convenience, there is also an infix operator to achieve the same thing:

    user.age ?= request.age

This will assign the unwrapped value to user.age as long as it was defined.

You might also like...
MediaType is a library that can be used to create Media Types in a type-safe manner.

This is a general purpose Swift library for a concept of typed treatment for Media Types. We use this library on clients and servers to speak the same dialect and to enjoy all the comfort strong types provide over raw strings.

Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types
Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types

Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types

A CMIO Camera Extension of the creative camera type, with configuration app

ArtFilm A CMIO Camera Extension of the creative camera type, with configuration app ArtFilm is the sample code for the blog post Getting To Grips With

Nano framework which defines Haskell's undefined in Swift.

undefined for Swift Micro frameworks are popular now, so I'll go nano framework :-). This is all the code: /** * `undefined()` pretends to be able to

Implement dynamic JSON decoding within the constraints of Swift's sound type system by working on top of Swift's Codable implementations.

DynamicCodableKit DynamicCodableKit helps you to implement dynamic JSON decoding within the constraints of Swift's sound type system by working on top

Type-safe CAAnimation wrapper. It makes preventing to set wrong type values.
Type-safe CAAnimation wrapper. It makes preventing to set wrong type values.

TheAnimation TheAnimation is Type-safe CAAnimation wrapper. Introduction For example, if you want to animate backgroundColor with CABasicAnimation, yo

Codable, but with Super power made custom Codable behavior easy.

Codable, but with Super power made custom Codable behavior easy.

Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

A phantom type is a custom type that has one or more unused type parameters.

PhantomTypes A phantom type is a custom type that has one or more unused type parameters. Phantom types allow you to enforce type-safety without sacri

Library of Swiftui Views conforming to Codable, meaning we can produce JSON driven UI!

CodableView Library of Swiftui Views conforming to Codable, meaning we can produce JSON driven UI! Adding a CodableView Type Create View that conforms

Codable code is a Swift Package that allows you to convert JSON Strings into Swift structs

Codable code is a Swift Package that allows you to convert JSON Strings into Swift structs.

Extensions giving Swift's Codable API type inference super powers 🦸‍♂️🦹‍♀️
Extensions giving Swift's Codable API type inference super powers 🦸‍♂️🦹‍♀️

Welcome to Codextended — a suite of extensions that aims to make Swift’s Codable API easier to use by giving it type inference-powered capabilities an

Type-safe observable values and collections in Swift

GlueKit ⚠️ WARNING ⚠️ This project is in a prerelease state. There is active work going on that will result in API changes that can/will break code wh

🎯 PredicateKit allows Swift developers to write expressive and type-safe predicates for CoreData using key-paths, comparisons and logical operators, literal values, and functions.
🎯 PredicateKit allows Swift developers to write expressive and type-safe predicates for CoreData using key-paths, comparisons and logical operators, literal values, and functions.

🎯 PredicateKit PredicateKit is an alternative to NSPredicate allowing you to write expressive and type-safe predicates for CoreData using key-paths,

Type-Erased Existential Generic AsyncSequence Values in Swift

AnyAsyncSequence AnyAsyncSequence allows you to expose AsyncSequence interfaces in your APIs without exposing the underlying sequence type, while cont

MQTagged provides a Tagged structure which helps differentiating between values of the same type.

MQTagged provides a Tagged structure which helps differentiating between values of the same type.

An original project making use of custom UITableViewCells, date formatting, json parsing, and handling user location.

SunTimes An original project making use of custom UITableViewCells, date formatting, json parsing, date and time formatting based on the json data, an

Type-safe event handling for Swift

emitter-kit v5.2.2 A replacement for NSNotificationCenter#addObserver and NSObject#addObserver that is type-safe and not verbose. import EmitterKit /

JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die
JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very important part of Pitaya.

Owner
David Monagle
David Monagle
A macOS application displaying the thermal, voltage and current sensor values.

Sensors About A macOS application displaying the thermal, voltage and current sensor values. License Project is released under the terms of the MIT Li

Jean-David Gadina 82 Jan 3, 2023
Store values using unique, randomly generated identifiers

Storage Store values using unique, randomly generated identifiers. This packages consists of three types: A Storage class, a UniqueIdentifiable protoc

Jordan Baird 1 Feb 23, 2022
Handling dimensional numbers with physical units in Swift made easy.

Dimensional arithmetics in Swift This package provides an easy and natural way of dealing with physical sizes. Performing complex arithmetics or unit

Niklas Nickel 1 May 27, 2022
Framework for easily parsing your JSON data directly to Swift object.

Server sends the all JSON data in black and white format i.e. its all strings & we make hard efforts to typecast them into their respective datatypes

Mukesh 11 Oct 17, 2022
Swift type modelling the success/failure of arbitrary operations.

Result This is a Swift µframework providing Result<Value, Error>. Result<Value, Error> values are either successful (wrapping Value) or failed (wrappi

Antitypical 2.5k Dec 26, 2022
Type-Safe Associated Objects in Swift

Type-Safe Associated Objects in Swift TSAO is an implementation of type-safe associated objects in Swift. Objective-C associated objects are useful, b

Lily Ballard 135 Dec 21, 2022
UTIKit is an UTI (Uniform Type Identifier) wrapper for Swift.

UTIKit UTIKit is an UTI (Uniform Type Identifier) wrapper for Swift. Features UTIKit is a full featured library including entire UTI functions. Conver

Hiroki Kato 254 Nov 27, 2022
Swift package for accessing SF Symbols in a type safe manner.

Swift Package Information Code Coverage Swift package for accessing SF Symbols in a type safe manner. Features ?? Contains all SF Symbols - 1.0, 2.0,

null 6 Dec 7, 2021
DeviceGuru is a simple lib (Swift) to know the exact type of the device

DeviceGuru DeviceGuru is a simple lib (Swift) to know the exact type of the device, e.g. iPhone 6 or iPhone 6s Easy to use Light weight From version 5

Inder Kumar 442 Dec 28, 2022
🚀Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.

??Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.

Cheng Zhang 18 Mar 9, 2022