Skip to content

Instantly share code, notes, and snippets.

@fitomad
Last active June 27, 2023 07:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitomad/096704e1cd81ec80ceff4b32e5467b85 to your computer and use it in GitHub Desktop.
Save fitomad/096704e1cd81ec80ceff4b32e5467b85 to your computer and use it in GitHub Desktop.
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)
}
@wptechprodigy
Copy link

Cool...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment