Decodable codable

My notes on Decodable and Encodable in swift

Why Use Decodable / Encodable?


  • Decodable & Encodable are standard, so more people will know how to use them
  • has some nice enum trickery (nested enum keys etc)


  • You could achive all of what these new features offer with reflection.

  • Must implement another required init for all subclasses


  • Nice simple example:

  • CodableKeys: (aka custom keys if json keys differ)

  • Decode inheritance:

  • Nice official apple article:

  • init(decoder) ;

  • Decode and Encode extensions:


struct Whale:Decodable,Encodable{
	let name:String
	let whaleType:String
let json = """
 "name": "The Whale",
 "whaleType": "Blue Whale"
""".data(using: .utf8)! // our data in native (JSON) format

//Global generic decode method for Decodable
func decode<T:Decodable>(data: Data) throws -> T {
	let decoder = JSONDecoder()
	return try decoder.decode(T.self, from: data)

//Encodable Extension
extension Encodable {
    func encode() throws -> Data {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        return try encoder.encode(self)
let whale:Whale = try decode(data: json)//From json to struct
let whaleJSON = try whale.encode()//From struct to json


Real KVC:

Tut with playground: nested JSON structures