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

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 .