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:
- Getting the path to a known file in your app bundle (nil means you forgot to target the file during development).
- Force casting a call to
UITableView dequeueReusableCell
(nil means you have a mistake in your storyboard).
- Getting a specific component from DateComponents when you just specially asked Calendar for that component (nil mean you have a typo).
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:
- Dealing with any user input. Never assume a user enters valid data. Never assume a value can be converted as expected. Always check for
nil
results.
- Parsing JSON results. Never assume the data you get matches some expected format even if that format is clearly documented and always seems to work. Things change over time. Gracefully handle such unexpected data instead of just assuming a value will always be there and of the assumed data type.
- Dealing with any API that can
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…