Explicitly unwrapping optional nil does not cause crash

前端 未结 2 1694
不思量自难忘°
不思量自难忘° 2021-01-18 17:05

A few folks asked this question before, yet no answer was accepted.

I have a UITableViewCell that contains a UITextField.

If I clic

2条回答
  •  萌比男神i
    2021-01-18 17:39

    One way to think this as a choise of the API Implementor. If implementor handles the input arguments it will not be any problem to the API User.

    Lets create a drawing text class which just prints at console.

    class TextDrawer {
    
      var mustBeText: String!
    
      func renderText(string: String) {
          print(string)
      }
    
      func renderSafely() {
         renderText(string: self.mustBeText ?? "Nothing found to be rendered")
         // or 
         if let safeString = self.mustBeText {
            renderText(string: safeString)
         }
      }
    
      func renderUnsafely() {
          renderText(string: mustBeText)
      }
    }
    

    We have defined the mustBeText as String! means we are allowed to expect any string as well as nil argument.

    Now, as we create a instance of the class as below:

    let textDrawer = TextDrawer()
    textDrawer.mustBeText = nil // this is allowed since the `mustBeText` is `String!`.
    
    textDrawer.renderSafely() // prints -- Nothing found to be rendered
    
    textDrawer.renderUnsafely() // crashes at runtime.
    

    The renderUnsafaly() will crash since its not handling the nil case.

提交回复
热议问题