Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to force unwrap an optional after checking it is not nil

Tags:

swift

I have a network method that return me a completion closure with an Error as the parameter.

I usually avoid force unwrapping, but in that case, I use a guard statement to check if error is not nil:

guard error == nil else {
    print(error!)
    return
}

...

The method I'm calling is from an SDK so I don't really know what happens in there.

In general, is this force unwrapping thread safe or not?

like image 485
Nico Avatar asked Feb 19 '18 02:02

Nico


People also ask

What will happen if you try to unwrap an optional that contains nil like so?

Unwrap an optional type with the nil coalescing operator If a nil value is found when an optional value is unwrapped, an additional default value is supplied which will be used instead. You can also write default values in terms of objects.

Should you force unwrap Swift?

Hopefully you can see the difference between the two: one situation is guaranteed to work 100% of the time, and the other “should” work or “will nearly always work”. That's the key here: you should never force unwrap something that won't succeed 100% of the time. That's it – that's the entire rule.

What is force unwrapping?

In these cases, Swift lets you force unwrap the optional: convert it from an optional type to a non-optional type. For example, if you have a string that contains a number, you can convert it to an Int like this: let str = "5" let num = Int(str)

How do I stop forced unwrapping in Swift?

Your function may crash if you make some spelling error, and type the name of a different variable instead of middleName, but that would be a bug anyway and the crash would lead you to the bug. But usually "if let ... " is the better way to handle this, because it combines the test and the unwrapping.


1 Answers

The difference between if and guard is just simple, but in your case, you should use if, not guard. guard should be used when some values are expected to be present for the function to execute as intended. You don't want error to be present, but if it is not nil, you have to return. So you should use if let:

if let error = error {
    print(error)
    return
}

This way, you don't need to use force unwrapping and it improves how your code is represented.

Back to your question "In general, is this force unwrapping thread safe or not?", assuming that you are really talking about thread safety, it is certainly thread safe. Closure variables are immutable.

If you are talking about safety (ie will "fatal error: unexpectedly found nil while unwrapping an Optional value" occur), it is also certainly safe. error must not be nil before you can unwrap it (because of guard), so the force unwrapping is safe.

In conclusion, your current code is bulletproof, but using if let might be better.

like image 113
Papershine Avatar answered Sep 22 '22 13:09

Papershine