mskw
mskw

Reputation: 10308

Unwrapping optionals causing crash seem counter intuitive

I know Swift has a rule that says if you try to unwrap an Optional that contains a nil, it crashes.

Just a thought, if I want a type to be Optional (allow nil or a value), why would I want my program to crash if I unwrap it even if I explicitly say nil is allowed for my type?

Upvotes: 0

Views: 115

Answers (3)

Luca Angeletti
Luca Angeletti

Reputation: 59496

Unwrapping an optional means getting the (non nil) value inside the Optional. If the optional contains nil then the crash is pretty correct.

There are several ways to conditionally unwrap an optional value

E.g.

let name: String? = nil

if let

if let name = name {
    print(name)
}

guard let

guard let name = name else { return }
print(name)

inline conditional

name?.uppercaseString

Upvotes: 1

ZGski
ZGski

Reputation: 2528

Simply put: you wouldn't want your application to crash. Optionals are great for when you may or may not need a value, but you want to assign a variable to a type just in case.

It's similar to wearing a helmet when riding a bike. You may or may not fall during your ride (assign a value), but if you do, you sure will be happy that you've got a helmet (prepared a variable) for the situation. Now if you don't fall and find the helmet useless (find nil), you simply keep pedaling on (handle for nil value). This is what we tend to do in code. If we find a nil value, we handle it accordingly so the program doesn't crash.

There are many ways to handle a nil returned value in Swift. Some of these techniques include, but aren't limited to:

Upvotes: 1

Max Pevsner
Max Pevsner

Reputation: 4104

To prevent undefined behaviour. If you want to do something with a property, you expect it to contain something. And if it's accidentally nil at that point you should be aware of it and act accordingly. There might be cases when trying to do something with a nil (if the app doesn't crash), the whole flow could just stuck.

Upvotes: 0

Related Questions