Skip to content

Instantly share code, notes, and snippets.

@xaphod
Created November 30, 2017 01:39
Show Gist options
  • Save xaphod/3fda8e584dd840e3a3564da8a5b25846 to your computer and use it in GitHub Desktop.
Save xaphod/3fda8e584dd840e3a3564da8a5b25846 to your computer and use it in GitHub Desktop.
Approach 1: Swift 4's Decodable when you don't know the type you're decoding
import Foundation
protocol KeyedStruct {
var type_: String { get set }
}
struct Inputs : Codable {
struct KeyStruct : KeyedStruct, Codable {
var type_: String
}
}
extension Inputs {
struct FooInput : KeyedStruct, Codable {
var type_: String = "FooInput"
var foo: Int
var floaty: Float
}
struct BarInput : KeyedStruct, Codable {
var type_: String = "BarInput"
var bar: Int
var floaty: Float
}
}
class Foo {
var input = Inputs.FooInput(type_: "FooInput", foo: 3, floaty: 3.14)
}
class Bar {
var input = Inputs.BarInput(type_: "BarInput", bar: 5, floaty: 5.58)
}
let fooinput = Foo.init().input
let data = (try? JSONEncoder().encode(fooinput))!
let jsonStr = String.init(data: data, encoding: .utf8)!
print(jsonStr)
let keyed = (try? JSONDecoder().decode(Inputs.KeyStruct.self, from: data))!
print(keyed.type_)
if keyed.type_ == "FooInput" {
let foo2 = (try? JSONDecoder().decode(Inputs.FooInput.self, from: data))!
print(foo2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment