Skip to content

Instantly share code, notes, and snippets.

@dejanskledar
Last active September 25, 2017 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dejanskledar/a7e755c16e050c7f5d71ad2a6addab3c to your computer and use it in GitHub Desktop.
Save dejanskledar/a7e755c16e050c7f5d71ad2a6addab3c to your computer and use it in GitHub Desktop.
Swift 4 Codable Protocol example in Playground
//
// Created by Dejan Skledar
// Equaleyes Solutions Ltd.
//
import UIKit
struct Sword: Codable {
private enum CodingKeys: String, CodingKey {
case name = "sword_name"
case size = "length"
case isValyrianSteel = "is_valyrian_steel"
}
let name: String
let size: Int
let isValyrianSteel: Bool
init(name: String, size: Int, isValyrianSteel: Bool) {
self.name = name
self.size = size
self.isValyrianSteel = isValyrianSteel
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
size = try values.decode(Int.self, forKey: .size)
isValyrianSteel = try values.decode(Bool.self, forKey: .isValyrianSteel)
}
public func encode(to encoder: Encoder) throws {
var values = encoder.container(keyedBy: CodingKeys.self)
try values.encode(name, forKey: .name)
try values.encode(size, forKey: .size)
try values.encode(isValyrianSteel, forKey: .isValyrianSteel)
}
}
let oathKeeper = Sword(name: "Oathkeeper", size: 120, isValyrianSteel: true)
if let jsonData = try? JSONEncoder().encode(oathKeeper) {
let jsonString = String(data: jsonData, encoding: .utf8)
}
let json = """
{
"length": 120,
"is_valyrian_steel": true,
"sword_name": "Oathkeeper"
}
"""
let data = json.data(using: .utf8)
let sword = try? JSONDecoder().decode(Sword.self, from: data!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment