Why create “Implicitly Unwrapped Optionals”, since that implies you know there's a value?

前端 未结 10 1659
深忆病人
深忆病人 2020-11-22 07:30

Why would you create a \"Implicitly Unwrapped Optional\" vs creating just a regular variable or constant? If you know that it can be successfully unwrapped then why create a

10条回答
  •  有刺的猬
    2020-11-22 08:08

    The rationale of implicit optionals is easier to explain by first looking at the rationale for forced unwrapping.

    Forced unwrapping of an optional (implicit or not), using the ! operator, means you're certain that your code has no bugs and the optional already has a value where it is being unwrapped. Without the ! operator, you would probably just assert with an optional binding:

     if let value = optionalWhichTotallyHasAValue {
         println("\(value)")
     } else {
         assert(false)
     }
    

    which is not as nice as

    println("\(value!)")
    

    Now, implicit optionals let you express having an optional which you expect to always to have a value when unwrapped, in all possible flows. So it just goes a step further in helping you - by relaxing the requirement of writing the ! to unwrap each time, and ensuring that the runtime will still error in case your assumptions about the flow are wrong.

提交回复
热议问题