I am fetching user's data as json from a service and decoding into Codable User struct. I can access that property where I've fetched the response but I want to access that User struct property somewhere else, let's say in another class, function, etc.
I'm new to this and I'm thinking the ideal approach is to "at the time of fetching, store that data into Core Data or User Defaults and then update my views accordingly.
Please suggest what's the best and appropriate approach or wether there is any way to access codable struct values directly.
Here is my codable struct -
struct User: Codable {
let name : String?
enum CodingKeys: String, CodingKey {
case name = "Name"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decodeIfPresent(String.self, forKey: .name)
}
}
The wrong way I'm accessing struct in some function is -
UserInfo.CodingKeys.name.rawValue
//Output is the key string - 'Name'
someReferenceToUser.name?Userneeds to be available to those classes/functions. Either you need to pass it to those elements or make it globally available in some way ... although, I'd look at how you would do this by passing the reference. You might consider Realm, but that might be to heavy weight for what you want to achieve