Last active
October 11, 2023 14:26
-
-
Save issuran/9eeb666acb2fe99cfacf7550983bfa76 to your computer and use it in GitHub Desktop.
Decoding anything
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 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