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 Playlist Browser with Swift Building the Music Library and Playlist Models Struct Initialization

brent rogers
brent rogers
2,159 Points

why do we add the () in the following let musicLibrary = MusicLibrary().library

why do we need to add the () in the following line of code?

let musicLibrary = MusicLibrary().library

2 Answers

Zachary Green
Zachary Green
16,359 Points

because you're calling the library method on what gets returned from the MusicLibrary method. if you had

let musicLibrary = MusicLibrary.library

then you saying that the MusicLibrary object itself has a method called library when in actuality the library method is in whatever object is returned from the MusicLibrary method

Sorry, I've read this several times and still don't understand the difference between:

let musicLibrary = MusicLibrary.library

and

let musicLibrary = MusicLibrary().library

From developer.apple.com Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.

() calls the designated initializer and returns an instance of the MusicLibrary.