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 trialJason Hernandez Berland
1,575 PointsWhy use the ! operator?
If if-let is safer, then why does the ! operator even exist? What are the use cases for each?
3 Answers
kaitlanlang
3,042 Points'Why not just use 'if let' all the time?'
Simple answer less coding as long as it's obvious it's safe, which makes you think why have an optional if you know it's safe? An example of when you'd use this code economic technique below.
You have a constant that has been defined but whose value is not set until say by the users first input, but you have defined this 'empty' constant way before user input. Now straight after user input assigning a value to this constant you can guarantee it will work.
However, if it was referenced prior to being set, a bad day you will have
It's a vague example I know, as the coder you will have a feel for when to be lazy and when to not.
Stephen McMillan
iOS Development with Swift Techdegree Graduate 33,994 PointsIf you are 100% sure that your function/object wasn't going to return nil then you can just use the ! operator to unwrap it - You need to be sure because if it does return Nil then your going to have a bad day. However, If you didn't know if the object was going to return Nil or some value then use 'If let'.
Jason Hernandez Berland
1,575 PointsThanks Stephen McMillan ! Why not just use 'if let' all the time?
Fernando Szymczak
17,372 PointsIs any of this still relevant since Xcode 6.3???
I ask because, since then, calling a function with an optional no longer returns "some" + value, it simply returns the value and in the case of returning nil it no longer gives an error. It made me think this completely removes the need to unwrap the optional by using either the bang operator ! or if let statement. Am I right?
Stanley Lim
209 PointsCan someone follow up with this question too? I'm curious also myself
Jason Hernandez Berland
1,575 PointsJason Hernandez Berland
1,575 PointsThanks Kaitlan Lang ! Think I understand but like you said, will probably have to learn the hard way and have my app crash in order to really get it. Would love to see someone put some more explicit examples in the forum.