Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.