Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build a Vending Machine App in Swift 2.0 Loading Data From a Resource Finishing Touches

Marcos Reboucas
Marcos Reboucas
12,890 Points

Isn't "return vendingMachine.selection.count" in collectionView's numberOfItemsInSection method "hard coded"?

When returning "return vendingMachine.selection.count" in collectionView's numberOfItemsInSection method, we're simply using the number of items in our 'selection' array implementation:

let selection: [VendingSelection] = [.Soda, .DietSoda, .Chips, .Cookie, .Sandwich, .Wrap, .CandyBar, .PopTart, .Water, .FruitJuice, .SportsDrink, .Gum]

But what if any of these items didn't exist in our data source, i.e. if we had got the data from the web? Shouldn't it be more appropriate to create an array with our 'inventory' objects and use it's count instead?

Chris Stromberg
Chris Stromberg
Courses Plus Student 13,389 Points

Sounds like you are answering your own question!?

If you already know what buttons your vending machine is going to have why can't you set it to the array of selections?

1 Answer


I am not 100% I understand your question..

But the count() method takes care of that.. if the array changes, the count will return the appropriate numbers of items in it. SO if you add or delete, you will always get an accurate count. So it's not "hardcoded" per say.

Hardcoded would be if I was to set the number of items with an integer.

return 2

If I am not answering the question right, please try to explain a bit further what you are asking.

Thank you

Marcos Reboucas
Marcos Reboucas
12,890 Points

Maybe I didn't explain myself correctly. What I meant is the array 'selection' is hardcoded inside VendingMachine Class. If you go to the plist, delete all the data and run the app you still have all 12 items in your screen, although of course they don't have any quantity or price anymore, and the app won't be able to throw any error in this situation. I know the implementation works in this example because we have the data inside the app and already know what will be 'received' but in a real scenario we should show to the user only the items we do have in our data source.