在Swift 3中使用泛型参数调用闭包时出现奇怪的崩溃

时间:2017-08-22 08:55:38

标签: swift generics crash closures

这里我有一个协议:

protocol CrashProtocol {
    associatedtype T

    static func tryCrash(_ dummyInt: Int,
                         with closure: ((T) -> Void))
}

实现它的基类:

class Crash<M>: CrashProtocol {
    typealias T = M

    class func tryCrash(_ dummyInt: Int,
                        with closure: ((M) -> Void)) {
        print("Crash tryCrash")
    }
}

派生类继承基类:

class DerivedCrash: Crash<DummyObject> {

    override class func tryCrash(_ dummyInt: Int, with closure: ((DummyObject) -> Void)) {
        super.tryCrash(dummyInt, with: closure)

        print("Derived tryCrash")
        let obj = DummyObject.init()
        closure(obj)
    }
}

现在每当我尝试

DerivedCrash.tryCrash(1) { _ in
            print("Never reach here")
}

我得到了一个&#34; EXC_BAD_ACCESS&#34;崩溃。您可以找到我的测试代码here。 我已完成调试的一部分,但只发现导致崩溃的内存地址指向Swift.Int实例,我不使用它。 如果我稍微改变调用代码,代码将在执行闭包后崩溃。

DerivedCrash.tryCrash(1) { (obj: DummyObject) in
    //print("Never reach here")
    print("print as expected and then crash")
}

如果有人在某些方面可以粉碎,我将非常感激......

1 个答案:

答案 0 :(得分:1)

我已将NSObject添加到associatedtype,现在它不会崩溃。 没有回答你的问题,但也许这个临时解决方案会帮助你

protocol CrashProtocol {
    associatedtype T: NSObject

    static func tryCrash(_ dummyInt: Int,
                         with closure: ((T) -> Void))
}

class Crash<M:NSObject>: CrashProtocol {
    typealias T = M

    class func tryCrash(_ dummyInt: Int,
                        with closure: ((M) -> Void)) {
        print("Crash tryCrash")
    }
}