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 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")