How to save a multidimensional array to UserDefaults

烂漫一生 提交于 2019-12-12 03:43:20

问题


Have created an Array like this in Swift

var MyArray: [String:[String:[Int]]] = [
    "xx": ["x1": [1, 2, 3], "x2": [4, 5, 6], "x3": [7, 8, 9]],
    "yy": ["y1": [10, 11, 12], "y2": [13, 14, 15], "y3": [16, 17, 18]]


]

And I wonder how to save this to the UserDefaults


回答1:


As @Eric mentioned in comment this is not a multidimensional array it is nested dictionary, so you can set it using set(_:forKey:) and get dictionary using dictionary(forKey:).

Save dictionary in UserDefaults

let defaults = UserDefaults.standard
defaults.set(MyDict, forKey:"DicKey")

Retrieve dictionary from UserDefaults

if let dic = UserDefaults.standard.dictionary(forKey: "DicKey") as? [String:[String:[Int]]]  {
    print(dic)
}


来源:https://stackoverflow.com/questions/41103511/how-to-save-a-multidimensional-array-to-userdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!