• Stars
    star
    1,488
  • Rank 30,380 (Top 0.7 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 5 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Codextended

Swift Package Manager Mac + Linux Twitter: @johnsundell

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 and conveniences. It’s not a wrapper, nor is it a brand new framework, instead it augments Codable directly in a very lightweight way.

Codable is awesome!

No third-party serialization framework can beat the convenience of Codable. Since it’s built in, it can both leverage the compiler to automatically synthesize all serialization code needed in many situations, and it can also be used as a common bridge between multiple different modules — without having to introduce any shared dependencies.

However, once some form of customization is needed — for example to transform parts of the decoded data, or to provide default values for certain keys — the standard Codable API starts to become really verbose. It also doesn’t take advantage of Swift’s robust type inference capabilities, which produces a lot of unnecessary boilerplate.

That’s what Codextended aims to fix.

Examples

Here are a few examples that demonstrate the difference between using “vanilla” Codable and the APIs that Codextended adds to it. The goal is to turn all common serialization operations into one-liners, rather than having to set up a ton of boilerplate.

🏢 Top-level API

Codextended makes a few slight tweaks to the top-level API used to encode and decode values, making it possible to leverage type inference and use methods on the actual values that are being encoded or decoded.

🍨 With vanilla Codable:

// Encoding
let encoder = JSONEncoder()
let data = try encoder.encode(value)

// Decoding
let decoder = JSONDecoder()
let article = try decoder.decode(Article.self, from: data)

🦸‍♀️ With Codextended:

// Encoding
let data = try value.encoded()

// Decoding
let article = try data.decoded() as Article

// Decoding when the type can be inferred
try saveArticle(data.decoded())

🔑 Overriding the behavior for a single key

While Codable is amazing as long as the serialized data’s format exactly matches the format of the Swift types that’ll use it — as soon as we need to make just a small tweak, things quickly go from really convenient to very verbose.

As an example, let’s just say that we want to provide a default value for one single property (without having to make it an optional, which would make it harder to handle in the rest of our code base). To do that, we need to completely manually implement our type’s decoding — like below for the tags property of an Article type.

🍨 With vanilla Codable:

struct Article: Codable {
    enum CodingKeys: CodingKey {
        case title
        case body
        case footnotes
        case tags
    }

    var title: String
    var body: String
    var footnotes: String?
    var tags: [String]

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        title = try container.decode(String.self, forKey: .title)
        body = try container.decode(String.self, forKey: .body)
        footnotes = try container.decodeIfPresent(String.self, forKey: .footnotes)
        tags = (try? container.decode([String].self, forKey: .tags)) ?? []
    }
}

🦸‍♂️ With Codextended:

struct Article: Codable {
    var title: String
    var body: String
    var footnotes: String?
    var tags: [String]

    init(from decoder: Decoder) throws {
        title = try decoder.decode("title")
        body = try decoder.decode("body")
        footnotes = try decoder.decodeIfPresent("footnotes")
        tags = (try? decoder.decode("tags")) ?? []
    }
}

Codextended includes decoding overloads both for CodingKey-based values and for string literals, so that we can pick the approach that’s the most appropriate/convenient for each given situation.

📆 Using date formatters

Codable already comes with support for custom date formats through assigning a DateFormatter to either a JSONEncoder or JSONDecoder. However, requiring each call site to be aware of the specific date formats used for each type isn’t always great — so with Codextended, it’s easy for a type itself to pick what date format it needs to use.

That’s really convenient when working with third-party data, and we only want to customize the date format for some of our types, or when we want to produce more readable date strings when encoding a value.

🍨 With vanilla Codable:

struct Bookmark: Codable {
    enum CodingKeys: CodingKey {
        case url
        case date
    }

    struct DateCodingError: Error {}

    static let dateFormatter = makeDateFormatter()

    var url: URL
    var date: Date

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        url = try container.decode(URL.self, forKey: .url)

        let dateString = try container.decode(String.self, forKey: .date)

        guard let date = Bookmark.dateFormatter.date(from: dateString) else {
            throw DateCodingError()
        }

        self.date = date
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(url, forKey: .url)

        let dateString = Bookmark.dateFormatter.string(from: date)
        try container.encode(dateString, forKey: .date)
    }
}

🦹‍♀️ With Codextended:

struct Bookmark: Codable {
    static let dateFormatter = makeDateFormatter()

    var url: URL
    var date: Date

    init(from decoder: Decoder) throws {
        url = try decoder.decode("url")
        date = try decoder.decode("date", using: Bookmark.dateFormatter)
    }

    func encode(to encoder: Encoder) throws {
        try encoder.encode(url, for: "url")
        try encoder.encode(date, for: "date", using: Bookmark.dateFormatter)
    }
}

Again, we could’ve chosen to use a CodingKeys enum above to represent our keys, rather than using inline strings.

Mix and match

Since Codextended is 100% implemented through extensions, you can easily mix and match it with “vanilla” Codable code within the same project. It also doesn’t change what makes Codable so great — the fact that it often doesn’t require any manual code at all, and that it can be used as a bridge between frameworks.

All it does is give Codable a helping hand when some form of customization is needed.

Installation

Since Codextended is implemented within a single file, the easiest way to use it is to simply drag and drop it into your Xcode project.

But if you wish to use a dependency manager, you can either use the Swift Package Manager by declaring Codextended as a dependency in your Package.swift file:

.package(url: "https://github.com/JohnSundell/Codextended", from: "0.1.0")

For more information, see the Swift Package Manager documentation.

You can also use CocoaPods by adding the following line to your Podfile:

pod "Codextended"

Contributions & support

Codextended is developed completely in the open, and your contributions are more than welcome.

Before you start using Codextended in any of your projects, it’s highly recommended that you spend a few minutes familiarizing yourself with its documentation and internal implementation (it all fits in a single file!), so that you’ll be ready to tackle any issues or edge cases that you might encounter.

To learn more about the principles used to implement Codextended, check out “Type inference-powered serialization in Swift” on Swift by Sundell.

This project does not come with GitHub Issues-based support, and users are instead encouraged to become active participants in its continued development — by fixing any bugs that they encounter, or improving the documentation wherever it’s found to be lacking.

If you wish to make a change, open a Pull Request — even if it just contains a draft of the changes you’re planning, or a test that reproduces an issue — and we can discuss it further from there.

Hope you’ll enjoy using Codextended! 😀

More Repositories

1

Publish

A static site generator for Swift developers
Swift
4,763
star
2

SwiftTips

A collection of Swift tips & tricks that I've shared on Twitter
3,971
star
3

Files

A nicer way to handle files & folders in Swift
Swift
2,456
star
4

Ink

A fast and flexible Markdown parser written in Swift.
Swift
2,336
star
5

Unbox

[Deprecated] The easy to use Swift JSON decoder
Swift
1,956
star
6

Plot

A DSL for writing type-safe HTML, XML and RSS in Swift.
Swift
1,946
star
7

Marathon

[DEPRECATED] Marathon makes it easy to write, run and manage your Swift scripts 🏃
Swift
1,869
star
8

ImagineEngine

A project to create a blazingly fast Swift game engine that is a joy to use 🚀
Swift
1,818
star
9

SwiftPlate

Easily generate cross platform Swift framework projects from the command line
Swift
1,766
star
10

Splash

A fast, lightweight and flexible Swift syntax highlighter for blogs, tools and fun!
Swift
1,735
star
11

TestDrive

Quickly try out any Swift pod or framework in a playground
Swift
1,597
star
12

ShellOut

Easily run shell commands from a Swift script or command line tool
Swift
836
star
13

Wrap

[DEPRECATED] The easy to use Swift JSON encoder
Swift
732
star
14

CollectionConcurrencyKit

Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.
Swift
730
star
15

Sweep

Fast and powerful Swift string scanning made simple
Swift
531
star
16

Playground

Instantly create Swift playgrounds from the command line
Swift
439
star
17

Require

Require optional values to be non-nil, or crash gracefully
Swift
414
star
18

XcodeTheme

My Xcode theme - Sundell's Colors
Swift
408
star
19

AsyncCompatibilityKit

iOS 13-compatible backports of commonly used async/await-based system APIs that are only available from iOS 15 by default.
Swift
377
star
20

Shapeshift

Quickly convert a folder containing Swift files into an iPad-compatible Playground
Swift
339
star
21

Identity

🆔 Type-safe identifiers in Swift
Swift
298
star
22

SwiftBySundell

Code samples from the Swift by Sundell website & podcast
Swift
289
star
23

SwiftScripting

A list of Swift scripting tools, frameworks & examples
235
star
24

SuperSpriteKit

Extensions to Apple's SpriteKit game engine
Objective-C
224
star
25

Flow

Operation Oriented Programming in Swift
Swift
217
star
26

Xgen

A Swift package for generating Xcode workspaces & playgrounds
Swift
189
star
27

IndieSupportWeeks

A two-week effort to help support indie developers shipping apps on Apple's platforms who have been financially impacted by the COVID-19 pandemic.
183
star
28

CGOperators

Easily manipulate CGPoints, CGSizes and CGVectors using math operators
Swift
148
star
29

Animate

Declarative UIView animations without nested closures
Swift
129
star
30

SplashPublishPlugin

A Splash plugin for the Publish static site generator
Swift
92
star
31

Assert

A collection of convenient assertions for Swift testing
Swift
69
star
32

UITestingExample

Example code from my blog post about UI testing
Swift
67
star
33

Marathon-Examples

A collection of example Swift scripts that can easily be run using Marathon
Swift
55
star
34

Releases

A Swift package for resolving released versions from a Git repository
Swift
51
star
35

BlockSnippets

Xcode snippets that are very handy when working with blocks in various contexts
51
star
36

PlotPlayground

A Swift playground that comes pre-loaded with Plot, that can be used to explore the new component API.
Swift
49
star
37

SwiftKit

A collection of Swift utilities that I share across my Swift-based projects
Swift
38
star
38

UnitTestingWorkshop

Project used during my workshop "Getting started with unit testing in Swift"
Swift
36
star
39

JSUpdateLookup

A lightweight, easy to use Objective-C class to check if your iOS app has an update available
Objective-C
28
star
40

SwiftAveiro

Skeleton project for my Swift Aveiro workshop "Everyone is an API designer"
Swift
15
star
41

CloudKitChat

A demo chat application powered by CloudKit
Objective-C
14
star
42

swiftbysundell-beta-feedback

Submit your feedback on the Swift by Sundell 2.0 beta
9
star
43

JSGeometry

A set of utility functions that enables easy one-line manipulation of CoreGraphics geometry structs like CGPoint, CGSize & CGRect.
Objective-C
6
star
44

JSAutoCopy

An Objective-C category that enables automatic copying of any object
Objective-C
4
star
45

UnboxDemoPlayground

A Swift Playground that comes setup with Unbox & Wrap, used in my CocoaHeads Stockholm presentation
Swift
3
star
46

JSAutoEncodedObject

Automatically encode or decode any Objective-C object
Objective-C
3
star
47

JSLocalization

An Objective-C class that enables dynamic localization of an iOS app.
Objective-C
3
star
48

MarathonTestScriptWithDependencies

A test script with dependencies - used for Marathon's tests
Swift
2
star
49

JSObservableObject

Easily add protocol-based observation to any Objective-C class
Objective-C
2
star
50

MarathonTestPackage

A Swift package that's used in Marathon's tests
Swift
1
star
51

MarathonTestScript

A Swift script that's used in Marathon's tests
Swift
1
star