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
Alexander Certosimo
1,774 Pointsshould you be using optionals whenever retrieving from an array or enum?
hey all,
this may be a stupid question, but it seems to me that using optionals is a safe thing to do. So my thoughts were should you use an optional whenever getting a value from an array or enum? It seems like a safe thing to do just in case you made a mistake or even just a typo. I just wanted to get some input on these thoughts. Again, i apologize if this is a stupid question!
thank you
1 Answer
Sam Chaudry
25,519 PointsHi Alexander - Not a stupid question! As always it depends optionals are a great and useful feature in Swift. From personal experience I would say go with optionals as when you are passing/getting values around as you might not always get what you expect.
So if you have an array of Strings and when you call it to get the value out there isn't one i.e. It is nil optionals can safe guard against it, by simply using a ?. It will allow the programme to fail gracefully and allow the thread of execution to continue.
From what I have found is that using optionals are particularly useful when downloading data from the web in JSON format. There maybe a case where a value is missing from a key and you have to safe guard against it and optionals are really handy. So again I would lean to the side where defiantly get into the habit of using it.
In Swift 2.0 the introduction of guard statements to the Swift syntax help reduce the amount of optional used especially when defining return statements.
Hope this answers your question.