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
Mikkel Storch
1,955 PointsWhat is an Optional?
Can somebody explain to me, what exactly an optional is and when to use one? Thanks ;)
1 Answer
Petar Zelenovic
11,356 PointsWhen you ask a question you expect an answer. Same with computers.
If there is no answer, you repeat the question.
Computers, on the other hand, have to be told that there might not be an answer, and they need to be told how to handle that situation, because computers are really, really literal. Way more than the most literal human.
So, when you define a function, you declare the return type: string, integer, boolean or etc. If the return value (answer) is nil/null then the computer doesn't know what to do with the answer, as it was not declared as the possible return value. So your program crashes, and therefore you have to go back to the drawing table and re-define the function, you re-declare the return type is [string, integer, boolean or etc.] BUT there might be no answer. You, my dear computer, might encounter NIL. And then you tell the computer how to handle that situation.
That is an optional. You tell the computer the return is of some type, but you do not remove the option that the return value might be nil.
I hope this helps.
Cheers.