swift - 在 Swift 3 中使用泛型参数调用闭包时发生奇怪的崩溃

标签 swift generics crash closures

这里我有一个协议(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/

相关文章:

ios - Apple Watch 的 url 图片

swift - Swift 中 Storyboard 中的 "No @implementation found for the class"错误

json - 如何使用 ObjectMapper 映射不同类型?

generics - kotlin,如何返回泛型类型成员变量

ios - 如何在我的 Swift XCode 应用程序上设置 SwiftyJSON?

java - 如何在java中将通用对象添加到列表中?

c# - Autofac 注册通用委托(delegate)工厂

android - 我的应用程序在尝试禁用主页按钮时崩溃

android - Xamarin Android服务崩溃

c++ - JPEG 数据错误时 libjpeg 解码崩溃