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

Optionals and unwrapping?

Hi my question is on optionals. Ik optionals are used when there is a chance that a value can be nil but I can't get my head around optional Binding. I know the purpose behind it is to make sure that the optional value is safely unwrapped as to not trigger an error, but how exactly is that accompolished

in this code ive not exactly used optional binding as in the if let and its ran fine I have no errors and when i access the optional value middle name it shows that it is nil

struct Human {
    let initialName: String
    let middleName: String?
    let finalName: String

    func printFullName() -> String {

        if  middleName == nil {
        return initialName + finalName

        } else {

        return printFullName()
        }

    }

}

let friends = Human(initialName: "Albus", middleName: "Percival", finalName: "Dumbledore")
friends.middleName  

so if I haven't unwrapped it what have i done? what is the difference between optional binding and unwrapping?

How do you unwrap and use optional binding?

This code example might be better

// if 
var testing: String?
testing = "This String is a Optional"

if testing != nil {
print("This value is NOT nil")

} else {
print("This value IS nil")

}

//// IF Let
if let test = testing {
print("Test is not nil")

} else {
print("Test is not nil")

}