Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dictionary extension for using @AppStorage

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What’s wrong with the codes?

>Solution :

You are missing the string key for the storage:

@AppStorage("data") private var data :  [String:String] = [:]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading