简体   繁体   English

在Swift 3中无法从Userdefaults检索字典数据

[英]Unable to retrieve dictionary data from Userdefaults in Swift 3

Do you guys can bring some light on the use of dictionaries with UserDefaults ? 你们可以对使用UserDefaults的字典有一些了解吗?

What I want to get is to pass a certain dictionary from a view controller to another one using UserDefaults. 我想要得到的是使用UserDefaults将某个字典从视图控制器传递给另一个。

var dict = [String : AnyObject?]()
dict = ["Name": "Henri", "Group": "A", "Category": "4"]
UserDefaults.standard.set.(dict, forKey: "MyDict")

Then I try to retrieve the data 然后我尝试检索数据

let retrieveDict = UserDefaults.standard.dictionary(forKey:"MyDict")

I got a nice nil answer in the console. 我在控制台中得到了一个很好的nil答案。 When I try with int or float types it is fine... Is there anything I am missing to make this dictionary ? 当我尝试使用int或float类型时,这很好。。。

First of all, your code won't compile. 首先,您的代码将无法编译。

Second, a dictionary with type [String, AnyObject?] make no sense because you'll be not able to set nil in UserDefaults. 其次,类型为[String, AnyObject?]的字典没有意义,因为您将无法在UserDefaults中设置nil You should use empty String maybe for that purpose. 您应该为此使用空字符串。

The working code could look like that : 工作代码如下所示:

    var dict = [String : Any]() // or maybe [String : String] if you sure about value type
    dict = ["Name": "Henri", "Group": "A", "Category": "4"]
    UserDefaults.standard.set(dict, forKey: "MyDict")
    let retrieveDict = UserDefaults.standard.dictionary(forKey:"MyDict")

Hope it helps you :) 希望它能对您有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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