In a method, how to access a structure's property with String parameter in dot syntax way

Sorry, maybe the title seemed hard to understand.

Here is the situation:

A structure with google API URL properties, which are wrapped together and will be stored as Data in userDefaults.
Code Block
struct googleApiLibrary: Codable {
    let authUrl: URL
    let tokenUrl: URL
    let userinfoUrl: URL
}

A function with a parameter, Its job is to retrieve the googleApiLibrary from UserDefault, decode back to structure and get the corresponding URL based on the parameter key provided.
Code Block
func loadGmailApiUrl(forKey key: String) -> URL {
guard let encodedValue = defaults.object(forKey: "gmailApiLibrary") as? Data,
       let decodedValue = try? JSONDecoder().decode(GmailApiLibrary.self, from: encodedValue) else { return }
    return decodedValue.<???>
  }


The problem that has bothered me for a long time is, how can I use the String parameter key, to access the structure's property (the appropriate URL to the key).







Replies

One possible solution would be using KeyPath for the parameter key:
Code Block
func loadGmailApiUrl(forKey key: KeyPath<GmailApiLibrary, URL>) -> URL? {
guard let encodedValue = defaults.object(forKey: "gmailApiLibrary") as? Data else {
print("No value for 'gmailApiLibrary'")
return nil
}
do {
let decodedValue = try JSONDecoder().decode(GmailApiLibrary.self, from: encodedValue)
return decodedValue[keyPath: key]
} catch {
print(error)
return nil
}
}


@OOPer, Thanks, I'm going to have a try.

And, I'm not sure. Maybe it's better to save the url stuff as dictionary, not structure?

Maybe it's better to save the url stuff as dictionary, not structure?

True. If you have some reason to use String key, it definitely is the better.