Articles, podcasts and news about Swift development, by John Sundell.

Useful Codable extensions

Published on 06 Jun 2018
Basics article available: Codable

Here's two extensions that I always add to the Encodable and Decodable protocols, which for me really make the Codable API nicer to use. By using type inference for decoding, a lot of boilerplate can be removed when the compiler is already able to infer the resulting type.

extension Encodable {
    func encoded() throws -> Data {
        return try JSONEncoder().encode(self)
    }
}

extension Data {
    func decoded<T: Decodable>() throws -> T {
        return try JSONDecoder().decode(T.self, from: self)
    }
}

let data = try user.encoded()

// By using a generic type in the decoded() method, the
// compiler can often infer the type we want to decode
// from the current context.
try userDidLogin(data.decoded())

// And if not, we can always supply the type, still making
// the call site read very nicely.
let otherUser = try data.decoded() as User

Support Swift by Sundell by checking out this sponsor:

Bitrise

Bitrise: My favorite continuous integration service. Automatically build, test and distribute your app on every Pull Request, and use a new powerful suite of add-ons to visualize your test results, to ship your app with ease, and to add crash and performance monitoring to your project. Get started for free.