隐式打开可选选项是一种实用的妥协,可以使混合环境中的工作与现有的Cocoa框架及其约定进行互操作更加愉快,同时还允许逐步迁移到更安全的编程范式——没有空指针——由Swift编译器强制执行。
Swift的书,在基础章节,部分隐式打开可选项说:
Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization, as described in Unowned References and Implicitly Unwrapped Optional Properties.
…
You can think of an implicitly unwrapped optional as giving permission for the optional to be unwrapped automatically whenever it is used. Rather than placing an exclamation mark after the optional’s name each time you use it, you place an exclamation mark after the optional’s type when you declare it.
This comes down to use cases where the non-nil-ness of properties is established via usage convention, and can not be enforced by compiler during the class initialization. For example, the UIViewController properties that are initialized from NIBs or Storyboards, where the initialization is split into separate phases, but after the viewDidLoad() you can assume that properties generally exist. Otherwise, in order to satisfy the compiler, you had to be using the
forced unwrapping,
optional binding
or optional chaining
only to obscure the main purpose of the code.
Swift书中的上述部分也参考了自动引用计数章节:
然而,还有第三种情况,在这种情况下,两个属性都应该有一个值,并且在初始化完成后,两个属性都不应该为nil。在这种情况下,将一个类上的无主属性与另一个类上隐式展开的可选属性结合起来是很有用的。
这使得在初始化完成后可以直接访问这两个属性(不需要可选的展开),同时仍然避免了引用循环。
这归结于不是垃圾收集语言的怪癖,因此保留周期的破坏是由程序员来承担的,隐式地打开可选选项是隐藏这个怪癖的工具。
这涵盖了“何时在代码中使用隐式展开的可选选项?””的问题。作为应用程序开发人员,您将在用Objective-C编写的库的方法签名中遇到它们,而Objective-C没有表达可选类型的能力。
在Cocoa和Objective-C中使用Swift,部分使用nil:
Because Objective-C does not make any guarantees that an object is non-nil, Swift makes all classes in argument types and return types optional in imported Objective-C APIs. Before you use an Objective-C object, you should check to ensure that it is not missing.
In some cases, you might be absolutely certain that an Objective-C method or property never returns a nil object reference. To make objects in this special scenario more convenient to work with, Swift imports object types as implicitly unwrapped optionals. Implicitly unwrapped optional types include all of the safety features of optional types. In addition, you can access the value directly without checking for nil or unwrapping it yourself. When you access the value in this kind of optional type without safely unwrapping it first, the implicitly unwrapped optional checks whether the value is missing. If the value is missing, a runtime error occurs. As a result, you should always check and unwrap an implicitly unwrapped optional yourself, unless you are sure that the value cannot be missing.
...在这里的另一边