Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How do i check if multiple values are the same?

I am creating a little emoji slot machine app as recommended in one of the tasks. I have got it to where my app generates 3 random emojis from an array but I was wondering how I could check to see if these 3 values are equal?

1 Answer

Hi Luke,

The most simple way I can think of is to run a for loop over an array and count each selection as I've done in the below example, to do this I've done the following.

  • Created a new dictionary called counters
  • Check if the selection exists in the dictionary, if not assign each selection via the for loop
  • Increment the count of the selection by 1
  • Finally check if the selection has a total count of 3, if it is set the winner variable to true

The rest of the code is pretty self explanatory.

var selections = ["Test", "Test", "Test"]
var counters = [String: Int]()
var winner = false

// Count each selection and store it's overall count in a new dictionary
for selection in selections {
    // Check if the selection exists in the dictionary, if it doesn't set it's default value to 0
    if !contains(counters.keys, selection) {
        counters[selection] = 0
    }

    // Increment the count for the selection
    counters[selection]!++

    // Check if the count for the selection equals 3, if it does we have a winner
    if counters[selection] == 3 {
        winner = true
        break
    }
}

// Do we have a winner?
if winner {
    println("We have a winner, nice one.")
} else {
    println("You've lucked out!")
}

Hope that helps.