Skip to content

Instantly share code, notes, and snippets.

@aguilarpgc
Created February 3, 2018 23:58
Show Gist options
  • Select an option

  • Save aguilarpgc/6a9a2c0b924ea87d89851371a2ca0f4b to your computer and use it in GitHub Desktop.

Select an option

Save aguilarpgc/6a9a2c0b924ea87d89851371a2ca0f4b to your computer and use it in GitHub Desktop.
Enum with associated values
//: Playground - noun: a place where people can play
import UIKit
struct Category1: Decodable {
let recordID : String?
let Year_when_Started : String?
let Problem_Name : String?
}
struct Category2: Decodable {
let Refused : String?
let Date_Given : String?
let recordID : String?
let Date_when_Next_Due : String?
}
struct Category3: Decodable {
var Address : String?
var City : String?
var Date_of_Birth : String?
var First_Name : String?
var Gender : String?
var Last_Name : String?
var Postal_Code : String?
var recordID : String?
}
enum Category {
case category1([Category1])
case category2([Category2])
case category3([Category3])
var url: String {
switch self {
case .category1(_): return "Category1"
case .category2(_): return "Category2"
case .category3(_): return "Category3"
}
}
}
// CHANGE THIS TO EITHER: .category1, .category2, .category3
let mainCategory: Category = .category1([])
extension Category: Decodable {
init(from decoder: Decoder) throws {
switch(mainCategory) {
case .category1(_):
self = try .category1(decoder.singleValueContainer().decode([Category1].self))
case .category2(_):
self = try .category2(decoder.singleValueContainer().decode([Category2].self))
case .category3(_):
self = try .category3(decoder.singleValueContainer().decode([Category3].self))
}
}
}
// CHOOSE EITHER EXAMPLE OF THESE JSON TO MATCH THE CATEGORY:
// Example: JSON Category1
let json1 = """
[
{"recordID": "111"},
{"recordID": "222", "Year_when_Started" : "2000"},
{"recordID": "333", "Year_when_Started" : "2011", "Problem_Name" : "Problem1"}
]
""".data(using: .utf8)!
// // Example: JSON Category2
//let json1 = """
//[
//{"Refused": "refused1"},
//{"Refused": "refused2", "Date_Given": "2017", "recordID": "record4"},
//{"Refused": "refused3", "recordID": "record4", "Date_when_Next_Due": "2018"}
//]
//""".data(using: .utf8)!
// // Example: JSON Category3
//let json1 = """
//[
//{"Address": "address1", "City" : "city1", "First_Name" : "Name1"},
//{"Address": "address2", "City" : "city2", "First_Name" : "Name2", "Last_Name": "LastName2"},
//{"Address": "address3", "City" : "city3", "First_Name" : "Name3", "Last_Name": "LastName3", "Postal_Code": "code3"},
//]
//""".data(using: .utf8)!
let data1 = try JSONDecoder().decode(Category.self, from: json1)
print(data1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment