This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
var drinks = """ | |
{ | |
"drinks": [ | |
{ | |
"type": "water", | |
"description": "All natural" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Drinks: Decodable { | |
let drinks: [Drink] | |
enum DrinksKey: CodingKey { | |
case drinks | |
} | |
enum DrinkTypeKey: CodingKey { | |
case type | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Drink: Decodable { | |
var type: String | |
var description: String | |
private enum CodingKeys: String, CodingKey { | |
case type | |
case description | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var drinks = """ | |
{ | |
"drinks": [ | |
{ | |
"type": "water", | |
"description": "All natural" | |
}, | |
{ | |
"type": "orange_juice", | |
"description": "Best drank with breakfast" |