Lesson 21 - cardArray vs generateCards

Hi there,

Brand new to coding, Swift and CWC. Here goes,

In lesson 21 (Card Match app) we declare a new class, CardModel, in which we have a method, getCards, in which we declare an array generateCards into which we add the randomly generated cards and shuffle them. We then go to the ViewController and generate another array, cardsArray into which we execute the getCards method. My question, why declare a new array (cardsArray) when we already have one doing the same job (generateCards)?

Thanks :slight_smile:

cardArray belongs to the class ViewController.
generatedCardsArray belongs to class CardModel.

Neither can see the others array BUT there is a method to call the model to generate the array of cards and return that to the calling class.

So what we do in ViewController is that model is of type CardModel() which is a reference to the class CardModel. Then we declare and array of cardArray which is of type [Card].

We then say, “Hey model, can you get me an array of Cards?”
we do that by asking our reference to CardModel through the variable model to getCards() which executes the function in the CardModel class getCards(), which has a return type of [Card], when finished returns and array of [Card] buy saying return generatedCardsArray.

I hope that helps.

Thank you Chris. It is clearer. If I may push the friendship…

Why go through the double process of assigning CardModel to model (’’’ let model = CardModel() ‘’’) and then call the method getCards() rather than just call the method directly from the CardModel class?


You could do it this way:

cardArray = CardModel().getCards()

but that’s not the generally accepted coding convention in Swift.

If there is only ever one location in your code where getCards() is called then I guess it is arguable that you could do it as per above.

In my case I have configured the game to be able to be restarted so there is more than one model.getCards() call and I also subscribe to the generally accepted Swift coding conventions.

Each to his own I guess.