我正在尝试从字典数组中访问以下项目,我有两个问题(两种方法都不同)。字典数组初始化如下:
var testingArray = [[String: String]()]
testingArray.append(["name": "Ethiopia", "url": "localhost:8088"])
testingArray.append(["name": "Bugatti", "url": "localhost:8088"])
testingArray.append(["name": "Brazil", "url": "localhost:8088"])
testingArray.append(["name": "Jasmine", "url": "localhost:8088"])
testingArray.append(["name": "Hello", "url": "localhost:8088"])
第一种方法:
for (k,v) in testingArray {
// code here
}
因为(在for循环初始化的行上显示)而无法运行:
"Expression type '[[String : String]]' is ambiguous without more context
第二种方法:
for indices in testingArray {
for(k, v) in indices {
print(indices.keys)
}
}
返回以下内容:
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Ethiopia"], _transform: (Function))
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Ethiopia"], _transform: (Function))
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Bugatti"], _transform: (Function))
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Bugatti"], _transform: (Function))
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Brazil"], _transform: (Function))
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Brazil"], _transform: (Function))
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Jasmine"], _transform: (Function))
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Jasmine"], _transform: (Function))
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Hello"], _transform: (Function))
LazyMapCollection<Dictionary<String, String>, String>(_base: ["url": "localhost:8088", "name": "Hello"], _transform: (Function))
这是我想要实现的伪代码:
for(int i = 0; i < sizeOfArray; i++ {
print testingArray[i]."name"
print testingArray[i]."url"
}
我已经对此感到头疼了好几天,但我不太清楚它的成语足以单独解决这个问题,任何帮助都会非常感激(特别是如果我们能弄明白如何获得#1)工作)。
答案 0 :(得分:5)
我同意错误信息令人困惑/误导。但是for (k,v) in testingArray
没有意义,因为testingArray
是一个数组,而不是字典。它的元素是字典。
我认为你正在寻找这样的东西:
for obj in testingArray {
print(obj["name"])
print(obj["url"])
}
答案 1 :(得分:0)
这有效
for (k,v) in testingArray.enumerated() {
for (_, element) in k.enumerated(){
guard let elem = element.value as? [String: Any] else {
continue
}
print elem["name"]
}
}