在初始化程序的实现中必须完成什么?
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")
}
}
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.和。仍然保留显式分配
与初始化
措辞上的微小差异。因此,我会放弃选项 b,因为 b
和 c
变量不需要任何显式值,隐式 nil
暂时就可以了(不过,读取 c
还无法工作)
因此我的答案选择是选项a。在init方法之后,所有属性都需要有一些特定的值。其中一些在 init 函数中显式存在,一些则隐式存在。
tl;博士:
my final answer is Option a.
关于ios - 在初始化程序的实现中必须完成什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32937814/