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

前端 未结 3 1615
时光取名叫无心
时光取名叫无心 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条回答
  •  -上瘾入骨i
    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?.

提交回复
热议问题