Reputation: 77
I've looked at a few different posts on here and I cant seem to get what I'm specifically trying to do to work. I'm trying to declare an empty array of dictionaries. The problem is every time I try to iterate over each dictionary in the array(without running) I get an error basically saying that the way I set up the array isn't correct. This code is in my slide to delete function so it can't be run without the user populating the array of dicts first. Here is my code.
var leagueList = [Dictionary<String, Array<String>>]()
for dict in leagueList {
let key = dict.key as String!
if key == deletedAge {
self.leagueList.removeValue(forKey: deletedAge!)
}
}
Upvotes: 0
Views: 260
Reputation: 8729
You have a couple of things going on here.
You've properly declared leagueList
as an array of dictionaries using generics. That's cool.
Your issues are:
1) self.leagueList.removeValue(forKey: deletedAge!)
is looking for a key within an array. Arrays don't have keys, so you would get an error there.
2) dict.key
appears to assume there is a single key in the dictionary. While dict
is correctly a dictionary, Swift assumes it will have multiple keys. So, if you wanted to iterate through them (even if there's only one present) you'd have to use dict.keys
instead.
If you're simply wanting to remove the deletedAge
key's value for each dictionary in the leagueList
array, an easy way to do that is:
var leagueList = [Dictionary<String, Array<String>>]()
for var dict in leagueList {
dict.removeValue(forKey: deletedAge!)
}
Upvotes: 1
Reputation: 4729
It looks like you are trying to search through your array of dictionaries and remove a specific key from each one. To do that you need to use a two dimensional loop:
for var dict in leagueList {
for key in dict.keys {
if key == "someKey" {
dict.removeValue(forKey: key)
}
}
}
Upvotes: 0