我有一个字典,其中包含另一个 Dictionary
,后者包含一个 Array
,后者包含自定义类的另一个 Array
。我在处理这些问题时遇到了很多麻烦,谁能轻松告诉我定义、初始化、访问和分配给任一部分的方式。
Dic = [String: [String: [[MyClass]]]]
对不起,如果它令人困惑。
最佳答案
此代码向您展示了如何按照您的要求进行操作,但是您所要求的数据结构使用起来非常麻烦。我建议重新考虑您要完成的任务并查看此数据结构。
class MyClass {
var name : String
init(name: String) {
self.name = name
}
}
// Create your dictionary
var dic : [String: [String: [[MyClass]]]] = [:]
// Create a list of MyClass object
var list = [MyClass(name: "first"), MyClass(name: "second"), MyClass(name: "third")]
// Create a dictionary with string key and array of array of type MyList
var myClassDic = ["test": [list]]
// update or add new value via the updateValue method
dic.updateValue(myClassDic, forKey: "index1")
// update or add new value via the subscript
dic["index2"] = ["test2": [[MyClass(name: "forth"), MyClass(name: "fith")]]]
// Iterate over your outer dictionairy
for key in dic.keys {
// retrieve an entry from your outer dictionary
var tempDic = dic[key]
// Iterate over your inner dictionary
for sKey in tempDic!.keys {
// retrieve an array of array of MyList Object
var containerList = tempDic![sKey]
// iterate over the outer array
for listVal in containerList! {
//Iterate over the inner array
for sListVal in listVal {
print("\(sListVal.name) ")
}
println()
}
}
}
关于ios - 如何在容器中使用 Swift 特定的容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28123274/