How to avoid force unwrapping a variable?

前端 未结 5 2096
北海茫月
北海茫月 2020-11-30 13:56

How do I avoid using the ! operation doing a force unwrap as using this is usually a bad option.

What is the better option with code like the following where using

5条回答
  •  失恋的感觉
    2020-11-30 14:22

    In this case, your instructor is wrong. Your function is absolutely safe. middleName will not change from not nil to nil behind your back. 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.

    There are also situations where you don't say "if it's nil, it will crash, that's bad" but "if it's nil then I want it to crash" (usually because you know it can only be nil if there is a bug somewhere in your code). In that case ! does exactly what you want.

提交回复
热议问题