Rook1
Rook1

Reputation: 27

How to iterate through a dictionary that has multiple values per key in Swift

My goal with this code is to iterate through a dictionary where the keys are a specific college and the values of those keys are the college colors. When a user chooses their college by typing it into a textfield, the background changes to their college colors. When I used just one color iterating through the dictionary worked flawlessly but now that I have introduced a secondary color my code keeps breaking with the error "For-in loop requires '[UIColor]' to conform to 'Sequence'", here is my code. I would appreciate any help

For my dictionary I used Color Literal to easily choose a color:

var collegeDict = ["UCLA": [#colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1), #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)], "Stanford": [#colorLiteral(red: 0.3098039329, green: 0.01568627544, blue: 0.1294117719, alpha: 1), #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)]]

This is the iterator where the error appears:

    @IBAction func Button1Pressed(_ sender: Any) {
        for (key, colors) in collegeDict {
            for (primaryColor, secondaryColor) in colors {
            if collegeName == textField1.text {
                self.View1.backgroundColor = primaryColor
                self.Button1.backgroundColor = primaryColor

Upvotes: 3

Views: 196

Answers (1)

vadian
vadian

Reputation: 285064

for (primaryColor, secondaryColor) in colors is actually the (index, element) syntax but then you have to add .enumerated()

for (primaryColor, secondaryColor) in colors.enumerated()

Nevertheless even with enumerated() the syntax makes no sense at all.

Wait, it does make (a sort of) sense this way

@IBAction func Button1Pressed(_ sender: Any) {
    for (_, colors) in collegeDict {
        for (index, color) in colors.enumerated() {
        if collegeName == textField1.text {
            switch index {
                case 0: self.View1.backgroundColor = color
                case 1: self.Button1.backgroundColor = = color
                default: break
            }
            

This is the serious solution:

colors is an array and you can get the first and second element with index subscription

 @IBAction func Button1Pressed(_ sender: Any) {
    for (_, colors) in collegeDict {
        if collegeName == textField1.text {
            self.View1.backgroundColor = colors[0]
            self.Button1.backgroundColor = colors[1]

Actually the comparison if collegeName == textField1.text { which is not related to the loop makes no sense, too.

Upvotes: 1

Related Questions