从“[任何]?”投射到不相关的类型'[String : String?]'总是失败的问题

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

我使用此代码通过 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 [:]
        }
    }}

但是第 if let settings = UserDefaults.standard.array(forKey: "AppSettings") as? [String: String?] 行导致警告:

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

知道如何在 UerDefaults 中保存该词典吗?

替换这个

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

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

当你存储字典时,不要使用 .array(forKey,returns [Any]? 肯定不能转换为 [String:String?]


也来自Docs

同步()

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

所以评论

UserDefaults.standard.synchronize()