ios - 澄清 Swift 中类的可失败初始化器

标签 ios swift initialization

在结构中,初始化失败在属性设置为初始值之前触发。

但是,在类中,在设置所有属性并进行委托(delegate)后会触发失败。这是为什么?

为什么结构和类不能在初始化过程的最后触发初始化失败?

更新:

以下是 Apple Swift 文档中的示例代码:

在下面的结构例子中,初始化失败是在任何属性初始化之前触发的:

struct Animal {
    let species: String
    init?(species: String) {
        if species.isEmpty { return nil }
        self.species = species
    }
}

在下面的class例子中,设置属性后触发初始化失败:

class Product {
    let name: String!
    init?(name: String) {
        self.name = name
        if name.isEmpty { return nil }
    }
}

文档继续说明:

For classes, however, a failable initializer can trigger an initialization failure only after all stored properties introduced by that class have been set to an initial value and any initializer delegation has taken place.

为什么在类中,只有在所有属性都设置为它们的初始值(并发生委托(delegate))之后才会发生初始化失败?

最佳答案

如@mustafa 在 this 中所述帖子:

According to Chris Lattner this is a bug. Here is what he says:

This is an implementation limitation in the swift 1.1 compiler, documented in the release notes. The compiler is currently unable to destroy partially initialized classes in all cases, so it disallows formation of a situation where it would have to. We consider this a bug to be fixed in future releases, not a feature.

Source

关于ios - 澄清 Swift 中类的可失败初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31667740/

相关文章:

ios - 更新 CoreData 中的项目不会刷新 tableView

iPhone SpeakHere 1 个 channel 上的示例录音

ios - UITextfield稳定性?

ios - 按年、月、日排序时出现问题

swift - 计算红色的色相角范围

iOS swift : init not being fired?

python - 使用相同参数重复初始化类的最佳实践(金字塔)?

iphone - 将 UITextField 文本值转换为 bool 值

ios - xcode UI元素约束布局

C++ 类数组初始化