Last active
June 27, 2023 07:49
-
-
Save fitomad/096704e1cd81ec80ceff4b32e5467b85 to your computer and use it in GitHub Desktop.
This file contains 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
import Foundation | |
// | |
// MODEL | |
// | |
public struct Show: Codable { | |
public var name: String | |
public var network: String | |
} | |
public struct Season: Codable { | |
public var seasonNumber: Int | |
public var year: Int | |
} | |
public struct Episode: Codable { | |
public var title: String | |
public var runtime: Int | |
} | |
// | |
// FUNCTION | |
// | |
func decode<T: Codable>(_ type: T.Type, from string: String) -> T? { | |
let decoder = JSONDecoder() | |
if let data = string.data(using: .utf8), let object = try? decoder.decode(type, from: data) { | |
return object | |
} | |
return nil | |
} | |
// | |
// DATA | |
// | |
let jsonShow = """ | |
{ | |
"name" : "House of Cards", | |
"network" : "Netflix" | |
} | |
""" | |
let jsonSeason = """ | |
{ | |
"seasonNumber" : 1, | |
"year" : 2013 | |
} | |
""" | |
let jsonEpisode = """ | |
{ | |
"title" : "Pilot", | |
"runtime" : 52 | |
} | |
""" | |
let jsonShows = """ | |
[ | |
{ | |
"name" : "House of Cards", | |
"network" : "Netflix" | |
}, | |
{ | |
"name" : "The Big Bang Theory", | |
"network" : "CBS" | |
} | |
] | |
""" | |
// | |
// EXAMPLE | |
// | |
if let show = decode(Show.self, from: jsonShow) { | |
print(show) | |
} | |
if let season = decode(Season.self, from: jsonSeason) { | |
print(season) | |
} | |
if let episode = decode(Episode.self, from: jsonEpisode) { | |
print(episode) | |
} | |
if let shows = decode([Show].self, from: jsonShows) { | |
print(shows) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool...