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

Cristian Saguil
Cristian Saguil
2,143 Points

Would force unwrapping be better to use in this situation?

Here is my code - I have an optional String value for the year in a Car class. I know that in the videos, Pasan stresses to never use force unwrapping, but I feel like it would make more sense to just check: if year != nil, then force unwrap if the condition checks out. That way I dont have to create a new constant called carYear. What do you think?

class Car {

var make: String
var model: String
var year: String?

init(make: String, model: String, year: String?) {
    self.make = make
    self.model = model

    if let carYear = year {
        self.year = carYear
    } else {
        self.year = nil
    }
}

}

1 Answer

Cristian, eveyone has their preferences. The Swift documentation gives this example as one way to unwrap an optional (forced unwrapping):

if convertedNumber != nil {
    print("convertedNumber has an integer value of \(convertedNumber!).")
}
// Prints "convertedNumber has an integer value of 123."

They have this to say about it:

"Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value."

The next section is about optional binding, which is another way, and the one Pasan apparently prefers.

But Apple doesn't say or even imply that one is better than the other. I'm sure best practices will evolve. Indeed, for unwrapping using guard may win out over both.