There are cases where you forgot to set a value (so it's actually a bug), and running the program with forced unwrapping can crash the problem, and that can allow you to track down the bug where you forgot to set the value that you should have set.
From posts talking about avoiding forced unwrapping, it's always brought up that forced unwrapping can crash the program therefore it's a bad thing. What's so bad about crashing a problem when it actually has a bug?
Please give examples where forced unwrapping can be bad.
(I'm not saying forced unwrapping is suitable for everything.)
Even though Swift isn't sure the conversion will work, you can see the code is safe so you can force unwrap the result by writing ! after Int(str) , like this: let num = Int(str)! Swift will immediately unwrap the optional and make num a regular Int rather than an Int? .
Heck, even if you're 99.999% certain that it's safe, you shouldn't be using it – that equates to one crash in 100,000, which is really bad. Instead, force unwraps should be reserved for times when your code is absolutely guaranteed to be safe, as demonstrated above.
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.
Forced unwrapping (and I'm going to include force-casting as well) should only be used when you, as the programmer, know for a fact that an optional will never actually ever be nil
unless that nil
represents a clear bug in your code during development (and then you want it to crash).
There are many examples where this type of forced unwrapping is appropriate. Examples include:
UITableView dequeueReusableCell
(nil means you have a mistake in your storyboard).There are obviously many other cases where forced-unwrapping is appropriate but you must have a clear understanding of those cases.
But there are just as many runtime decisions that result in optionals that you can't guarantee and such cases should not be forced unwrapped.
Examples include:
nil
results.throw
or return optional results. Things can go wrong. Errors happen. Never assume you will get back a valid answer. Code defensively.In the end, a developer with the proper experience and understanding of how optionals work, what they mean, and when a value may or may not ever actually be nil
is in a position to safely use forced unwrapping when appropriate. Use it wisely.
Never use forced-unwrapping just because Xcode suggested it to make the compiler happy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With