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 trialNIKOLA RUSEV
5,293 Pointsfirst example with optioanal bindings
struct Person {
let firstName: String
let middleName: String?
let lastname: String
func fullName() -> String{
if let midName = middleName {
return "\(firstName) + \(midName) + \(lastname)"
}else {
return "\(firstName) + \(lastname)"
}
}}
i think that first example using if let should look like above.
So I don't understand the advantage of optional bindings over force unwrapping. In both cases in func
we give two option to be nil or not only deferent syntax so why force unwrapping is bad choice? i believe that Pasan is right and highly recommended to not use force unwrapping just cant figure out why. can someone explain to me?
3 Answers
NIKOLA RUSEV
5,293 Pointsif i first provide check for nil like this:
func fullName () -> String { if middleName == nil { return firstName + " " + lastname } else { return firstName + " " + middleName! + " " + lastname }}} will my app crash?
becouse pasan in video said that IF WE FORGET TO MAKE CHECK FOR NIL. and in teachers note there is some doc about optional said "The problem is that even though it might look obvious to you that middleName canβt be nil within the if, itβs not obvious to the compiler." sorry for bothering you just give me short answer
if i be careful with checking nil wil my app crash?
Jeroen de Vrind
29,772 PointsHi, with force unwrapping you're program can crash if the optional that you force unwrap is nil at that point. With optional binding you provide logic if the optional is not nil and skip that logic or provide an else clause in case the optional is not nil. Your program won't crash in this case.
Jeroen de Vrind
29,772 PointsJeroen de Vrind
29,772 PointsIf you check for nil first then you're sure that it can't be nil and u can force unwrap safely. Personally i try to avoid force unwrap as much as possible.