初始化器的实现必须完成什么?

What must be accomplished in the implementation of an initializer?

初始化器的实现必须完成什么?

a. All properties need to be initialized with a value

b. All properties need to be explicitly assigned a value.

c. All non-Optional properties need to be initialized.
   Sorry, that's incorrect. 
   Optionals need to be initialized as well.

d. The object needs to be created

哪个答案是正确的,为什么?

在我看来,这是一个非常令人困惑的问题。因为你作为开发者必须做的是选项c.

看看这个简单的代码示例和可编译的最小值init

class SomeClass {
    var a : AnyObject
    var b : AnyObject?
    var c : AnyObject!
    var d = ":)"

    init() {
        a = ""
        print("initialized")
    }
}

swift docu 状态

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition. These actions are described in the following sections.

选项d。恕我直言,因为对象创建是由底层运行时环境处理的,而不是通过初始化程序处理的。

现在b。和一个。保留 explicitly assignedinitialized 在措辞上的微小差异。因此,我会放弃选项 b,因为 bc 变量不需要任何显式值,隐式 nil 目前完全没问题(读取 c 将不起作用尽管如此)

因此我的答案选择是 选项 a。 在 init 方法之后,所有属性都需要有一些特定的值。其中一些在 init 函数中显式显示,一些隐式显示。

tl;博士:

my final answer is Option a.