Swift for循环:“表达式类型'[[String:String]]'在没有更多上下文的情况下是模糊的”

3 浏览
0 Comments

Swift for循环:“表达式类型'[[String:String]]'在没有更多上下文的情况下是模糊的”

我尝试从一个字典数组中访问以下项,并且我有两个问题(两种方法都不同)。字典数组的初始化如下:

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"
}

我已经在这个问题上纠结了几天,但我不知道swift及其惯用语好到足以独立解决这个问题,任何帮助都将非常感激(尤其是如果我们能找出如何让第1个方法工作的方法)。

admin 更改状态以发布 2023年5月22日
0
0 Comments

这个起作用

for (k,v) in testingArray.enumerated() {
    for (_, element) in k.enumerated(){
       guard let elem = element.value as? [String: Any] else {
            continue
       }
       print elem["name"]
    }
}

0
0 Comments

我认为这个错误信息很令人困惑/误导。但是for(k,v) in testingArray是没有意义的,因为testingArray是一个数组,不是一个字典。它的元素是字典。

我认为您是在寻找像这样的东西:

for obj in testingArray {
    print(obj["name"])
    print(obj["url"])
}

0