这里我有一个协议(protocol):
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")
}
我遇到“EXC_BAD_ACCESS”崩溃。你可以找到我的测试代码 here . 我已经完成了我的调试工作,但只发现导致崩溃的内存地址指向一个 Swift.Int 实例,我不使用它。 如果我稍微更改调用代码,代码将在执行闭包后崩溃。
DerivedCrash.tryCrash(1) { (obj: DummyObject) in
//print("Never reach here")
print("print as expected and then crash")
}
如果有人能切碎一些光线,我将不胜感激..
最佳答案
我已将 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")
}
}
关于swift - 在 Swift 3 中使用泛型参数调用闭包时发生奇怪的崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45813128/