此代码会生成 EXC_BAD_ACCESS(即使在 Playground 中)。
(我简化了代码以便更好地理解。)
准备工作:
// Playground - noun: a place where people can play
protocol EmptyInit {
init();
}
class FirstBase {
}
class SecondBase : EmptyInit {
required init(){
}
}
class A : FirstBase, EmptyInit{
required override init(){
}
}
class B : SecondBase, EmptyInit {
required init() {
}
}
很明显,您可以像这样创建 A
和 B
的实例。
A();
B();
假设需要使用泛型在函数内创建类的实例:
func creation<T: EmptyInit>(x a:T.Type) -> T{
var object = T()
return object;
}
当此代码运行时:
var b = creation(x: B.self);
此代码因 EXC_BAD_ACCESS 而崩溃
var a = creation(x: A.self);
link to the screenshot of the playground
这很奇怪,不是吗?我不明白。有任何想法吗? (甚至可能是 Swift 错误?)
最佳答案
更新 Swift 1.2 XCode 6.3 Beta 2(Beta 1 不起作用): 您的代码现在可以正常运行,并且达到预期结果:
var b = creation(x: B.self); //{__lldb_expr_9.SecondBase}
var a = creation(x: A.self); //{__lldb_expr_11.FirstBase}
它们发生冲突,因为 FirstBase 没有 init,但 EmptyInit 需要 init。 这样它就可以工作:
protocol EmptyInit {
init();
}
class FirstBase {
required init(){
}
}
class SecondBase : EmptyInit {
required init(){
}
}
class A : FirstBase, EmptyInit{
required init(){
}
}
class B : SecondBase, EmptyInit {
required init() {
}
}
A();
B();
func creation<T: EmptyInit>(x a:T.Type) -> T{
var object = T()
return object;
}
var b = creation(x: B.self); // SecondBase
var a = creation(x: A.self); // FirstBase
关于inheritance - 在 Swift 中使用泛型、协议(protocol)和继承创建对象时的 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27988949/