刘哲诚*_*刘哲诚 3 iterator for-loop swift
我试图从一个字典数组访问以下项目,我有两个问题(两者都是不同的方法).字典数组初始化如下:
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"])
Run Code Online (Sandbox Code Playgroud)
第一种方法:
for (k,v) in testingArray {
// code here
}
Run Code Online (Sandbox Code Playgroud)
由于(在for循环初始化的行上出现)将无法运行:
"Expression type '[[String : String]]' is ambiguous without more context
Run Code Online (Sandbox Code Playgroud)
第二种方法:
for indices in testingArray {
for(k, v) in indices {
print(indices.keys)
}
}
Run Code Online (Sandbox Code Playgroud)
返回以下内容:
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))
Run Code Online (Sandbox Code Playgroud)
这是我想要实现的伪代码:
for(int i = 0; i < sizeOfArray; i++ {
print testingArray[i]."name"
print testingArray[i]."url"
}
Run Code Online (Sandbox Code Playgroud)
我已经对这个问题感到头疼了好几天,但我不知道swift和它的成语足以单独解决这个问题,任何帮助都会非常感激(特别是如果我们能弄清楚如何让#1工作).
我同意错误信息令人困惑/误导.但for (k,v) in testingArray没有意义,因为testingArray是一个数组,而不是字典.它的元素是字典.
我想你正在寻找这样的东西:
for obj in testingArray {
print(obj["name"])
print(obj["url"])
}
Run Code Online (Sandbox Code Playgroud)