无法继承我的协议(命令因信号而失败:分段错误:11)

Can't inherit my protocol (Command failed due to signal: Segmentation fault: 11)

我为绑定块创建了一个小协议(这是 Swift 中 KVO 的一些循环) 代码在这里:

typealias storedClosure = (object: Any) -> Void

protocol BindingProtocol {
    var binders: [String : storedClosure]! { get set }
    func bind(string: String, block: storedClosure)
}

extension BindingProtocol {
    mutating func bind(string: String, block: storedClosure) {
        if binders == nil {
            binders = [String : storedClosure]()
        }
        binders[string] = block
    }
}

在我尝试继承此协议后,我遇到 Xcode 崩溃或编译错误,如 Command failed due to signal: Segmentation fault: 11

class View : UIView, BindingProtocol {
    var binders: [String : (object: Any) -> Void]!
}

有什么想法吗?

您的 属性 没有问题,但是您的方法...

protocol BindingProtocol {
    var binders: [String : storedClosure]! { get set }
    func bind(string: String, block: storedClosure) //<--- 1.This
}


extension BindingProtocol {
    mutating func bind(string: String, block: storedClosure) { //<--- 2.This
        if binders == nil {
            binders = [String : storedClosure]()
        }
        binders[string] = block
    }
}

您在第 1 点将方法定义为普通方法,并在第 2 点将其实现为变异方法。

它们具有相同的签名,但实际上是两种不同的方法。在这种情况下,Swift 没有找到合适的电话。这是我在使用默认实现的协议时遇到的一个常见问题。

一个解决方案就是改变...

protocol BindingProtocol {
    ...
    //From
    //func bind(string: String, block: storedClosure) 

    //To
    mutating func bind(string: String, block: storedClosure) 
}