Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Enumerations and Optionals in Swift Introduction to Optionals Optional Binding

NIKOLA RUSEV
NIKOLA RUSEV
5,293 Points

first 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
NIKOLA RUSEV
5,293 Points

if 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
Jeroen de Vrind
29,772 Points

If 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.

Jeroen de Vrind
Jeroen de Vrind
29,772 Points

Hi, 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.