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 trialJavier Cambon Sanjurjo
1,482 PointsWhy aren't all the types just optional by default?
In the sense that all would, by default, return nil if it is empty. Instead of having to add ?, !, IFs...
Thanks!
2 Answers
Chris Shaw
26,676 PointsHi Javier,
Making everything optional by default would be very cumbersome and would offer no practicality as you're creating a single method in which to write your code which makes it a static mess of if statements which is not what Swift is about, optional's should be treated as data with a value that can be nil
but offer a valid type of value at some other time.
To put this in a little bit more perspective if we made something like a String
an optional we would have to check if it's nil
first by using an IF LET
statement which would be confusing since it's never a nil
value but an object which has a series of characters inside it; turning String
into an optional would defeat the purpose of having methods such as isEmpty
which we use to check if the string has a value.
There are many different other examples but I think that puts some simple context behind why optional's are useful in the correct circumstances and not loosely used.
Javier Cambon Sanjurjo
1,482 PointsThanks Chris, that all makes a lot of sense.