1

I've built an array to generate 8 iterations of random pairs of cards for a total of 16 cards. However it is instead producing 17 cards. I can not see why it is producing this extra card or how to stop it.

I'm new to Xcode and Swift obviously so my debugging skills are Nil. I've inserted print statements and used breakpoints to try to understand where the extra card is coming from. It seems to be happening at the very start of the CardModel class, perhaps in the way I wrote the method at the beginning.

class CardModel {

    func getCards() -> [Card] {
        //print("2nd Check")
        // Declare an array to store the generated cards
        var generatedCardsArray = [Card()]

        print("number of random pairs \(generatedCardsArray.count)")

        // Randomly generate pairs of cards
        for _ in 1...8 {

            print("number of random pairs \(generatedCardsArray.count)")

            // Get a random number
            let randomNumber = arc4random_uniform(13) + 1

            // Log the number
            print("Random # \(randomNumber)")

            // Create the first card object
            let cardOne = Card()
            cardOne.imageName = "card\(randomNumber)"

            generatedCardsArray.append(cardOne)

            // Create the second card object
            let cardTwo = Card()
            cardTwo.imageName = "card\(randomNumber)"

            generatedCardsArray.append(cardTwo)

I expected this to output 16 random pairs but it is outputting 17

1

1 Answer 1

5

This line:

var generatedCardsArray = [Card()]

that you are using to initialise an empty array is actually creating an array with one entry. Try this instead:-

var generatedCardsArray : [Card] = []

You're then correctly generating 16 cards (8 pairs) but you already have one to start with, that's 17.

Sign up to request clarification or add additional context in comments.

1 Comment

Or var generatedCardsArray = [Card]()

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.