简体   繁体   中英

Cast from '[Any]?' to unrelated type '[String : String?]' always fails issue

I use this code to store app settings via UserDefaults:

var appSettings: [String: String?] {

    set { // On attempt to set new value for the dictionary
        UserDefaults.standard.set(newValue, forKey: "AppSettings")
        UserDefaults.standard.synchronize()
    }
    get { // On attempt to get something from dictionary
        if let settings = UserDefaults.standard.array(forKey: "AppSettings") as? [String: String?] {
            return settings
        } else {
            return [:]
        }
    }}

But line if let settings = UserDefaults.standard.array(forKey: "AppSettings") as? [String: String?] if let settings = UserDefaults.standard.array(forKey: "AppSettings") as? [String: String?] causes warning:

Cast from '[Any]?' to unrelated type '[String : String?]' always fails

Any ideas how to save this dictionary in UerDefaults?

Replace this

UserDefaults.standard.array(forKey: "AppSettings") as? [String: String?]

with

UserDefaults.standard.dictionary(forKey: "AppSettings") as? [String: String?]

as you store a dictionary so don't use .array(forKey which returns [Any]? that for sure can't be casted to [String:String?]


Also from Docs

synchronize()

Waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used.

so comment

UserDefaults.standard.synchronize()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM