Egor Iskrenkov
Egor Iskrenkov

Reputation: 443

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?] causes warning:

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

Any ideas how to save this dictionary in UerDefaults?

Upvotes: 1

Views: 2390

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

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()

Upvotes: 5

Related Questions