I understand I need to make Dictionary
conform to RawRepresentable
when using a dictionary with @AppStorage. Below is the furthest I got.
extension Dictionary: RawRepresentable where Key == String, Value == String {
public init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8), // convert from String to Data
let result = try? JSONDecoder().decode([String:String].self, from: data)
else {
return nil
}
self = result
}
public var rawValue: String {
guard let data = try? JSONEncoder().encode(self), // data is Data type
let result = String(data: data, encoding: .utf8) // coerce NSData to String
else {
return "[:]" // empty Dictionary respresented as String
}
return result
}
}
The extension compiles. But when I declare an empty dictionary it didn't work:
@AppStorage private var data : [String:String] = [:]
The error message is Missing argument for parameter #2 in call
What's wrong with the codes?
CodePudding user response:
You are missing the string key for the storage:
@AppStorage("data") private var data : [String:String] = [:]