inheritance - 在 Swift 中使用泛型、协议(protocol)和继承创建对象时的 EXC_BAD_ACCESS

标签 inheritance swift protocols swift-playground generics

此代码会生成 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() {

    }
}

很明显,您可以像这样创建 AB 的实例。

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/

相关文章:

java - 使用 Jackson 反序列化派生类

ios - 使用 willDisplay cell 方法向上滚动 tableView 时,如何从 API 获取数据并更新单元格和部分?

ios - 我在 xcworkspace 中收到大量关于丢失文件的警告

c++ - 基类不完整的继承

inheritance - 为什么我的嵌套 div 不继承父级高度?

objective-c - 为什么 Objective-c 协议(protocol)采用其他协议(protocol)?

ios - 如何符合协议(protocol)变量的设置和获取?

swift - 协议(protocol)在单元中被重置

python - 静态方法和继承设计

swift - 如何在 Realm 中执行检查相关对象属性的查询?