In Apple Swift, in what case(s) would I not want an implicitly unwrapped optional?

前端 未结 3 1616
时光取名叫无心
时光取名叫无心 2021-01-18 08:47

I believe I understand why optionals are handy (my best thought for use is to be able to return a nil Boolean value), but in what case would I want to declare a wrapped opti

相关标签:
3条回答
  • 2021-01-18 08:58

    Implicitly unwrapped optionals introduce a possible failure similar to dereferencing null pointers. You should only use them when you can be sure that no one will accidentally pass nil, or when you're comfortable telling clients of the interface that the function will crash if they violate the interface requirements.

    Another way to avoid using ? Repeatedly is the if let statement:

    func foo(bar:Int?) -> Int? {
      if let x = bar {
        if Int.max / x >= x {
          return x * x
        }
      }
      return nil
    }
    

    x here is an Int rather than Int?.

    0 讨论(0)
  • 2021-01-18 09:01

    First lets talk about what the point of ? is in swift. You might create a var that looks like this.

    var number : Int?
    

    You are basically saying that there is a possibility that this variable could be nil. If there is ever a possibility that an object could be nil, then you would not want to do something like this.

    var secondNumber = number! + 5
    

    Basically in that statement you are saying, there is a possibility this variable could be nil but, I will totally ignore that fact and pretend there is no way that it could be nil.

    Instead you will want to check if that variable exists first and then set it like so

    var number : Int?
    var number2 : Int?
    
    number = 10
    
    if let unwrappedNumber = number {
        number2 = unwrappedNumber + 5
    }
    

    Hope this helps!

    0 讨论(0)
  • 2021-01-18 09:17

    If you try to access the content of an implicitly unwrapped optional and there's nothing there, your app will crash.

    If you use the patterns for checking the content of an optional — like optional binding and optional chaining - you can control how your app should fail gracefully in unforeseen situations. And it doesn't make your code all that more complicated.

    Not crashing seems like a good reason to me.

    0 讨论(0)
提交回复
热议问题