澄清 Swift 中 类 的失败初始化器
Clarification on Failable Initializers for Classes in Swift
在结构中,在属性设置为初始值之前触发初始化失败。
但是,在 classes 中,在设置所有属性并进行委托后会触发失败。这是为什么?
为什么结构和 classes 都不能在初始化过程的最后触发初始化失败?
更新:
以下是 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.
为什么在 classes 中,只有在所有属性都设置为初始值(并进行委托)后才会发生初始化失败?
如@mustafa 在 this post 中所述:
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.
在结构中,在属性设置为初始值之前触发初始化失败。
但是,在 classes 中,在设置所有属性并进行委托后会触发失败。这是为什么?
为什么结构和 classes 都不能在初始化过程的最后触发初始化失败?
更新:
以下是 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.
为什么在 classes 中,只有在所有属性都设置为初始值(并进行委托)后才会发生初始化失败?
如@mustafa 在 this post 中所述:
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.