Reputation: 13
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
Upvotes: 1
Views: 55
Reputation: 1610
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.
Upvotes: 5