Skip to content

Instantly share code, notes, and snippets.

@yesleon
Forked from saiday/codable_polymorphism.swift
Last active April 28, 2020 09:44
Show Gist options
  • Save yesleon/7c39d2bb27923abdc37c86ad8b1e7833 to your computer and use it in GitHub Desktop.
Save yesleon/7c39d2bb27923abdc37c86ad8b1e7833 to your computer and use it in GitHub Desktop.
import Foundation
let json = """
{
"results":[
{
"blah":"blah",
"nested_object":{
"type":"a",
"id":69,
"aVar":"aaa"
}
},
{
"blah":"blah",
"nested_object":{
"type":"b",
"id":42,
"bVar":"bbb"
}
}
]
}
"""
// Types
protocol AbstractType {
var id: Int { get set }
}
struct SubtypeA: AbstractType {
var id: Int
var aVar: String
}
struct SubtypeB: AbstractType {
var id: Int
var bVar: String
}
// Response Types
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var blah: String
var nested_object: NestedObject
}
struct NestedObject: Codable {
var type: String
var id: Int
var aVar: String?
var bVar: String?
func getObject() -> AbstractType {
switch type {
case "a":
return SubtypeA(id: id, aVar: aVar!)
case "b":
return SubtypeB(id: id, bVar: bVar!)
default:
fatalError()
}
}
}
// Usage
let response = try JSONDecoder().decode(Response.self, from: json.data(using: .utf8)!)
let nestedObjects = response.results.map { $0.nested_object.getObject() }
let isA = nestedObjects[0] is SubtypeA
let isB = nestedObjects[1] is SubtypeB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment