-
-
Save yesleon/7c39d2bb27923abdc37c86ad8b1e7833 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 | |
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