gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:02:39 25 4
gpt4 key购买 nike

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

但是,在类中,在设置所有属性并进行委托(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com