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
John C.
297 PointsWhat's the purpose of optionals with Swift?
It seems pretty pointless and I can't think of an exact scenario where this would even be necessary. As a PHP developer I've never had to use labels, specify types and or specify what type the return value would be but adding a "?" after the return type and using "bangs !" to escape "structs" sounds a little over the top does it not? Is there really a reason for it?
http://teamtreehouse.com/library/functions-and-optionals/optionals/what-is-an-optional
1 Answer
Andres Oliva
7,810 PointsOut of Apple's Swift Programming Guide:
Here’s an example of how optionals can be used to cope with the absence of a value. Swift’s String type has a method called toInt, which tries to convert a String value into an Int value. However, not every string can be converted into an integer. The string "123" can be converted into the numeric value 123, but the string "hello, world" does not have an obvious numeric value to convert to.
The example below uses the toInt method to try to convert a String into an Int:
let possibleNumber = "123" let convertedNumber = possibleNumber.toInt() // convertedNumber is inferred to be of type "Int?", or "optional Int"
Because the toInt method might fail, it returns an optional Int, rather than an Int. An optional Int is written as Int?, not Int. The question mark indicates that the value it contains is optional, meaning that it might contain some Int value, or it might contain no value at all. (It can’t contain anything else, such as a Bool value or a String value. It’s either an Int, or it’s nothing at all.)
John C.
297 PointsJohn C.
297 PointsRight, but as the developer I would assume you'd know what values are going where and what types of values they are. If you need to convert a numeric string into an integer I can see the use for toInt() but again, I still don't see the importance of these "Optionals". I guess I'll have to see them being used in a beneficial way for them to make sense to me.