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

iOS Swift 2.0 Enumerations and Optionals Introduction to Optionals Optional Binding

Chris Lopez
Chris Lopez
8,155 Points

How does optional binding work with the first example of force unwrapping?

The only way they teach you how to use optional binding is from a dictionary. how does this work with the first example bellow:

struct Person { let firstName: String let middleName: String? let lastName: String

func getFullName() -> String {
    if middleName == nil {
        return firstName + " " + lastName
    } else {
        return firstName + " " + middleName! + " " + lastName
    }
}

}

let me = Person(firstName: "Chris", middleName: nil, lastName: "Lopez")

1 Answer

Chris Lopez
Chris Lopez
8,155 Points

For anyone else that is confused like I was, this is how you do it

struct Person {
    let firstName: String
    let middleName: String?
    let lastName: String

    func getFullName() -> String {
        if let MiddleName = middleName {
            return firstName + " " + MiddleName + " " + lastName
        } else {
            return firstName + " " + lastName
        }
}
}
let me = Person(firstName: "Chris", middleName: nil, lastName: "Lopez")