---
title: "#86: Decodable 🔩"
url: https://littlebitesofcocoa.com/86-decodable
author: Jake Marsh
date: 2015-09-21
published: 2015-09-21
topics: ["JSON","Models","Libraries"]
description: "We continue our look at frameworks that map JSON into model types today with Decodable by Johannes Lund. Decodable is another fantastic solution for this task."
---

# #86: Decodable 🔩

By Jake Marsh, September 21, 2015. HTML: https://littlebitesofcocoa.com/86-decodable

We continue our look at **frameworks** that map **JSON** into **model types** today with [Decodable](http://git.io/decodable) by [Johannes Lund](https://github.com/Anviking). _Decodable_ is another fantastic solution for this task. It takes advantage of **Swift 2's** new **error handling** functionality, and unlike [ObjectMapper](https://littlebitesofcocoa.com/84) (covered in [Bite #84](https://littlebitesofcocoa.com/84)), the **properties** on your **models** don't <i>need</i> to be **optionals**. Let's take a closer look:

To get things wired up we just need to implement the _Decodable_ **protocol** on our **model types**, like so:

``` swift
struct Spaceship {
  var captain: User
  var topSpeed: Double
}

extension Spaceship: Decodable {
  static func decode(j: AnyObject) throws -> Spaceship {
    return try Spaceship(
      captain: j => "captain",
      topSpeed: j => "topSpeed"
    )
  }
}
```

Then we can convert from **JSON** to one of these **structs** like this:

``` swift
do {
  let ship = try Spaceship.decode(json)
} catch let error { print(error) }
```

We can decode **JSON** **arrays** like this:

``` swift
do {
  let ships = try [Spaceship].decode(array)
} catch let error { print(error) }
```

_Decodable_ also handles **nested types** and is quite flexible. For example, we aren't even forced to use _Decodable_ on every **type**. Here we bypass _Decodable_ a bit and instantiate a **value** for our `rank` **property** manually:

``` swift
extension User: Decodable {
  static func decode(j: AnyObject) throws -> User {
    return try User(name: j => "name", rank: Rank(name: j => "rank"))
  }
}
```

Some other noteworth _Decodable_ features are its wonderful **printable errors**, and how easy it is to add **custom decode functions** for things like parsing custom **date formats**, etc.

More info about _Decodable_ can be found at [git.io/decodable](http://git.io/decodable)
