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 Build a Vending Machine App in Swift 2.0 Loading Data From a Resource Finishing Touches

How a constant of class instance is declared without initialization?

In this video, teacher declared

let vendingMachine: VendingMachine

but my understanding is all instance of a class need to initialized

in this case in VendingMachine class we have

required init(inventory: [VendingSelection: VendingItem]) { self.inventory = inventory }

How the declaration without initialization work?

Please fulfill my understanding

1 Answer

Hey Jiranan,

When creating objects or variables, we use two steps: first, we declare the variable, and then we initialise the variable. However, these steps don't necessarily need to be performed on the same line of code. For instance:

let vendingMachine: VendingMachine = VendingMachine(inventory: [someSelection: someItem]) // Two steps, one line

// We can also separate this line into the two steps it is actually doing under the hood:

let vendingMachine: VendingMachine // Declaring variable
vendingMachine = VendingMachine(inventory: [someSelection: someItem]) // Initialising variable

Both do the exact same thing, except the first one is condensed into a single line. You can read more on declaration and initialisation of variables here and here.

Hope this helps, Rodrigo

Thank you very much