I am trying to access the following items from an Array of dictionaries and I have two problems (both are different approaches). The array of dictionaries is initialized as follows:
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"])
The first method:
for (k,v) in testingArray {
// code here
}
Won't run due to (which appears on the line the for loop is initialized):
"Expression type '[[String : String]]' is ambiguous without more context
The second method:
for indices in testingArray {
for(k, v) in indices {
print(indices.keys)
}
}
returns the following:
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))
Here is pseudocode equivalent that I am trying to achieve:
for(int i = 0; i < sizeOfArray; i++ {
print testingArray[i]."name"
print testingArray[i]."url"
}
I have been scratching my head over this for days but I don't know swift and its idioms well enough to solve this alone, any help would greatly be appreciated (esp if we can figure out how to get #1 working).
I agree the error message is confusing/misleading. But for (k,v) in testingArray
doesn't make sense, because testingArray
is an array, not a dictionary. Its elements are dictionaries.
I think you're looking for something like this:
for obj in testingArray {
print(obj["name"])
print(obj["url"])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With