Skip to content

Instantly share code, notes, and snippets.

View Stoff81's full-sized avatar

Tom Stoffer Stoff81

  • inMusic
  • Auckland
View GitHub Profile
View DrinksCodable.swift
//: Playground - noun: a place where people can play
import UIKit
var drinks = """
{
"drinks": [
{
"type": "water",
"description": "All natural"
View DrinksCodable5.swift
struct Drinks: Decodable {
let drinks: [Drink]
enum DrinksKey: CodingKey {
case drinks
}
enum DrinkTypeKey: CodingKey {
case type
}
View DrinksCodable4.swift
let jsonDecoder = JSONDecoder()
do {
let results = try jsonDecoder.decode(Drinks.self, from:drinks.data(using: .utf8)!)
for result in results.drinks {
print(result.description)
if let beer = result as? Beer {
print(beer.alcohol_content)
}
}
} catch {
View DrinksCodable3.swift
class Beer: Drink {
var alcohol_content: String
private enum CodingKeys: String, CodingKey {
case alcohol_content
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.alcohol_content = try container.decode(String.self, forKey: .alcohol_content)
View DrinksCodable2.swift
class Drink: Decodable {
var type: String
var description: String
private enum CodingKeys: String, CodingKey {
case type
case description
}
}
View DrinksCodable1.swift
var drinks = """
{
"drinks": [
{
"type": "water",
"description": "All natural"
},
{
"type": "orange_juice",
"description": "Best drank with breakfast"