Post

Replies

Boosts

Views

Activity

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. 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. func loadGmailApiUrl(forKey key: String) -> URL { &#9;&#9;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).
3
0
329
Sep ’20
How to access Class's property in required convenience init?
Hi, I'm new to Swift. I am reading Mastering macOS Programming Chapterc13, about NSCoding, here is the code: class Person: NSObject, NSCoding {    var name: String let kName = "Name"    init(name: String) {   self.name = name   super.init() }    required convenience init?(coder: NSCoder) {   guard let name = coder.decodeObject(forKey: kName) as? String else { return nil } self.init(name: name)  }    func encode(with coder: NSCoder) { coder.encode(name, forKey: kName) } } And I got an error in line 12: 'self' used in property access 'kName' before 'self.init' call Of course, I just find rules in the Swift Language Guide - Initialization : Safety check 3 A convenience initializer must delegate to another initializer before assigning a value to any property (including properties defined by the same class). Maybe I am stuck here because I should init() before I can access the property kName. But I need to get the name and assigning to the init(name:) after Can someone tell me the best practice to solve it is? Thanks!
3
0
4.1k
Jul ’20