Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Why to declare "let vendingMachine: VendingMachineType" instead of "let vendingMachine: VendingMachine"

I was playing a little bit with the code and does it make more sense to declare the vendingMachine as a VendingMachine, what is the advantage to declare it as a VendingMachineType? I know one is a protocol and the other one a class. But the class already implements the protocol in the class.

Using the protocol allows more flexibility. For example, if you want your code to be able to handle a regular VendingMachine, and a SuperVendingMachine that both implement the same protocol you can use the protocol as the type for both.

Imagine you needed to create an array of these vending machines, both super and regular. You can actually make your array of the protocol type like [VendingMachineType] and you are allowed to put both vending machine types into the array as long as they implement the protocol. If you only used the VendingMachine class, then the SuperVendingMachines could not go into the array.