Skip to content

Instantly share code, notes, and snippets.

@issuran
Last active October 11, 2023 14:26
Show Gist options
  • Save issuran/9eeb666acb2fe99cfacf7550983bfa76 to your computer and use it in GitHub Desktop.
Save issuran/9eeb666acb2fe99cfacf7550983bfa76 to your computer and use it in GitHub Desktop.
Decoding anything
import UIKit
struct MyModel: Decodable {
let name: String
}
struct MyOtherModel: Decodable {
let otherName: String
}
var data =
"""
{
"name": "Tiago"
}
""".data(using: .utf8)!
func decode<T: Decodable>(modelType: T.Type) -> T {
let myStruct = try! JSONDecoder().decode(modelType, from: data)
return myStruct
}
let model: MyModel = decode(modelType: MyModel.self)
print(model.name)
data = """
{
"otherName": "Oliveira"
}
""".data(using: .utf8)!
let otherModel: MyOtherModel = decode(modelType: MyOtherModel.self)
print(otherModel.otherName)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment