ios - 在初始化程序的实现中必须完成什么?

标签 ios swift 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.和。仍然保留显式分配初始化措辞上的微小差异。因此,我会放弃选项 b,因为 bc 变量不需要任何显式值,隐式 nil 暂时就可以了(不过,读取 c 还无法工作)

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

tl;博士:

my final answer is Option a.

关于ios - 在初始化程序的实现中必须完成什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32937814/

相关文章:

ios - 您如何在iOS上录制PCM音频文件?

ios - 应用程序更新需要考虑什么?

ios - 我无法在 TableView 内加载 TableView 单元格

iphone - Objective-c 类初始值设定项执行多次

ios - 数据保护/NSFileProtectionComplete - 通过 entitlements.plist 成功支持?

ios - UIPickerView - 条件显示

ios - 在弧形中添加 UIButton

iphone - 即使应用程序终止也更新用户位置

Swift:在初始化程序中多次调用 Self.init

swift - 所需初始化的访问控制