Checking if randomNumber has already been generated

Howdy guys,

I am trying to finish get through the Matching card game - but am hitting some stumbling blocks when it comes to the random number generating. Chris alluded to this in the video, by using a while loop to get completely unique sets of numbers.

I cannot for the life of me, figure out how this is down.

Any help is appreciated.
As you can see I started to make another empty array, as well as a while loop but I keep getting to a spot where I don’t know how to proceed.

To have only unique values show here’s the steps I’d follow:

  1. Get a random number
  2. Use a for loop to check if that number has been used already
    3a. If it hasn’t, use that number
    3b. If it has, generate a new number. (Keep repeating until you find a unique number)

4a. Add this number to your used numbers array

I would do pretty much what @MikaelaCaron suggested, but use a Set<Int> instead of an Array. For this particular purpose it almost certainly won’t matter much, but with larger amounts of data using a Set will gain you better performance because testing whether a Set contains an item is faster than testing an Array. Also, you won’t need a loop to do the test.

Hi, I am also stuck here. And unfortunately the responses above didn’t help me :confused:

Check screenshot - compared to the example in the lesson when he’s inputting an integer back into an int array, for the card game we’re putting in a Card type into an array that accepts Card types. So when I try to use a WHILE LOOP - if generatedCards.contains(cardOne) == false { does not work. It gives an error that says: “Referencing instance method ‘contains’ on ‘Sequence’ requires that ‘Card’ conform to ‘Equatable’”

How do we resolve this?

Thank you!!!

In order to be able to compare two objects, you have to have some way of determining if they are equal or not. Thus the Equatable protocol. Int conforms to Equatable; Card does not. So you can compare integers but you can’t compare Cards. That’s why Chris used a generatedNumbersArray = [Int]() in the video.

So you have two options for fixing this:

  1. Make Card conform to Equatable. This can be done by giving Card an == method and then adding : Equatable to the class definition. Something like this:
class Card: Equatable {
    var imageName = ""
    var isFlipped = false
    static func == (lhs: Card, rhs: Card) -> Bool {
        lhs.imageName == rhs.imageName
  1. Don’t store the generated Card objects, store the random Ints like Chris does in his video.

Thank you so much @roosterboy!! :raised_hands: