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

jon kelson
jon kelson
5,149 Points

What is an optional Init / initialiser , and why do we need them ?

What is an optional Init / initialiser , and why do we need them ?

I understand the need for optionals Such as (name : String?) etc , but unsure why we need an Init optional .

Many thanks

2 Answers

Moritz Gruber
Moritz Gruber
12,073 Points

If your initialiser can return nil you use the optional initialiser (init?).

This is helpful because later xCode reminds you that you can get a nil value while initialising that object. If you assign the object to variable or constant it makes sure that it is also an optional type and forces you to take action while writing code.

Without the optional initialiser in this case you are likely to get an error when you app is running because you are trying to assign nil to something thats not an optional type , and its much harder to find and fix this error.

Cheers Moritz

jon kelson
jon kelson
5,149 Points

ok thanks Moritz , so,would i be right by saying you need to have an optional init with every optional object ? I need a bit more practice with optionals .