When should I compare an optional value to nil?

前端 未结 5 1534
时光取名叫无心
时光取名叫无心 2020-11-22 10:22

Quite often, you need to write code such as the following:

if someOptional != nil {
    // do something with the unwrapped someOptional e.g.       
    someF         


        
5条回答
  •  醉梦人生
    2020-11-22 11:08

    I think you should go back to the Swift programming book and learn what these things are for. ! is used when you are absolutely sure that the optional isn't nil. Since you declared that you are absolutely sure, it crashes if you're wrong. Which is entirely intentional. It is "unsafe and best avoided" in the sense that asserts in your code are "unsafe and best avoided". For example:

    if someOptional != nil {
        someFunction(someOptional!)
    }
    

    The ! is absolutely safe. Unless there is a big blunder in your code, like writing by mistake (I hope you spot the bug)

    if someOptional != nil {
        someFunction(SomeOptional!)
    }
    

    in which case your app may crash, you investigate why it crashes, and you fix the bug - which is exactly what the crash is there for. One goal in Swift is that obviously your app should work correctly, but since Swift cannot enforce this, it enforces that your app either works correctly or crashes if possible, so bugs get removed before the app ships.

提交回复
热议问题