0

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!)
    }
} 
3
  • Never mind, I may have read your question wrong. Edit: I did Commented Oct 12, 2017 at 17:24
  • What's the error and what are you actually trying to do? Commented Oct 12, 2017 at 17:25
  • What are you expecting dict.key to do? Dictionaries can have more than one key. Commented Oct 12, 2017 at 17:43

2 Answers 2

1

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!)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I've been stuck on that for a while and it's funny that I was just really overthinking it the whole time.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.