Unboxing - An extension for KeyedDecodingContainer class to decode a collection of heterogeneous types.

Related tags

Utility Unboxing
Overview

Unboxing

An extension for KeyedDecodingContainer class to decode a collection of heterogeneous types.

Usage

Start by creating an enum that has variants for the parsable type it must adhere to ClassFamily and define the type information discriminator.

enum DrinkFamily: String, ClassFamily {
    case drink = "drink"
    case beer = "beer"

    static var discriminator: Discriminator = .type
    
    typealias BaseType = Drink

    func getType() -> Drink.Type {
        switch self {
        case .beer:
            return Beer.self
        case .drink:
            return Drink.self
        }
    }
}

Later in your collection overload the init method to use our KeyedDecodingContainer extension.

class Bar: Decodable {
    let drinks: [Drink]

    private enum CodingKeys: String, CodingKey {
        case drinks
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        drinks = try container.decodeHeterogeneousArray(OfFamily: DrinkFamily.self, forKey: .drinks)
    }
}

let barJson = """
{
    "drinks":
    [
        {"type": "drink", "description": "All natural"},
        {"type": "beer", "description": "best drunk on fridays after work", "alcohol_content": "5%"}
    ]
}
""".data(using: .utf8)!

let bar = try JSONDecoder().decode(Bar.self, from: barJson)

Otherwise follow the below example to decode an Hetegerenous json array object.

let drinksJson = """
[
    {"type": "drink", "description": "All natural"},
    {"type": "beer", "description": "best drunk on fridays after work", "alcohol_content": "5%"}
]
""".data(using: .utf8)!

let drinks = try JSONDecoder().decodeHeterogeneousArray(OfFamily: DrinkFamily.self, from: drinksJson)

Installation

Swift Package Manager:

dependencies: [
    .package(url: "https://github.com/abdalaliii/Unboxing.git")
]

License

Unboxing is available under the MIT license. See the LICENSE file for more info.

You might also like...
Parsing indeterminate types with Decodable and Either enum using Swift

Decodable + Either Parsing indeterminate types with Decodable and Either enum us

A Swift μ-Library for Somewhat Dependent Types

Validated Validated is a μ-library (~50 Source Lines of Code) that allows you make better use of Swift's type system by providing tools for easily gen

Extensions for Swift Standard Types and Classes

Cent Cent is a library that extends certain Swift object types using the extension feature and gives its two cents to Swift language. Dollar is a Swif

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 command-line tool and Swift Package for generating class diagrams powered by PlantUML
A command-line tool and Swift Package for generating class diagrams powered by PlantUML

SwiftPlantUML Generate UML class diagrams from swift code with this Command Line Interface (CLI) and Swift Package. Use one or more Swift files as inp

An iOS app/Safari extension to automagically redirect AMP links to their normal counterpart. Comes with a trusty dog.

Amplosion ⚡️ Amplosion is an iOS 15 and greater app that automagically redirects AMP links to their normal counterpart. AMP links can be super annoyin

YMExtension - Swift extension

YMExtension Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installation YMExte

An extension for Xcode to generate builders from structs

Swift Struct Builder Generator Xcode Source Editor Extension An Xcode extension (plugin) to generate struct builders automatically. Install Swift Stru

Owner
Passionate iOS Engineer👨‍💻
null
Decode a string encoded in Base64 into an https link and launch it in Google Chrome

Decode a string encoded in Base64 into an https link and launch it in Google Chr

Jerry 0 Jan 2, 2022
CipherCode - iOS App to decode your secret message

CipherCode IOS App to decode/encode your secret message App App consist of welco

Doston Rustamov 0 Jan 15, 2022
A lightweight extension to Swift's CollectionDifference, supporting moves in addition to removals and insertions, critical when updating interfaces and managing reference types.

DifferenceTracker is a lightweight extension to Swift's CollectionDifference. It defines moves in addition to removals and insertions, critical when updating interfaces and managing reference types.

Giles Hammond 2 Nov 25, 2022
A collection of useful result builders for Swift and Foundation value types

Swift Builders A collection of useful result builders for Swift and Foundation value types. Motivation Arrays, dictionaries, and other collection-base

David Roman 3 Oct 14, 2022
How Swift standard types and classes were supposed to work.

How Swift standard types and classes were supposed to work. A collection of useful extensions for the Swift Standard Library, Foundation, and UIKit.

Goktug Yilmaz 3k Dec 22, 2022
Functional data types and functions for any project

Swiftx Swiftx is a Swift library containing functional abstractions and extensions to the Swift Standard Library. Swiftx is a smaller and simpler way

TypeLift 219 Aug 30, 2022
The ISO 8601 period/duration types missing in Foundation

PeriodDuration This library introduces a close equivalent to Java's PeriodDuration, motivated by the lack of support for this standard in Foundation.

David Roman 19 Jun 22, 2022
Numerals is a package containing additional numeric types for the Swift programming language.

swift-numerals Numerals is a package containing additional numeric types for the Swift programming language. Contents The package currently provides t

Alexandre H. Saad 0 Jul 28, 2022
Swift package adding fraction and percentage types.

swift-rationals Rationals is a package containing Fraction and Percentage types for the Swift programming language. Contents The package currently pro

Alexandre H. Saad 0 Jul 28, 2022
Swift package adding measurable types.

swift-measures Measures is a package containing measurable types for the Swift programming language. Contents The package currently provides the follo

Alexandre H. Saad 1 Nov 5, 2022