如何在协议上创建约束

How to create constraint on protocol

我试图创建只能由继承自 UIView 的 类 实现的协议,令我惊讶的是这段代码编译没有错误(在 Swift 3.0 中):

protocol TestsProtocol {
    func test()
}

extension TestsProtocol where Self: UIView { }

class FooClass: TestsProtocol {

    func test() {

    }
}

我们可以看到 FooClass 不继承自 UIView,使用协议扩展我不想强制只有继承自 UIView 的 类 可以实施它。 据我所知,这不会在 Swift 2.1

中编译

您不能在 Swift 中执行此操作。扩展语法做了其他事情:

extension TestsProtocol where Self: UIView {
    func useful() {
        // do something useful
    }
}

现在任何 class 实现了 TestsProtocol 并且是 UIView(或子class)也有 useful() 函数。

您可以通过限制协议从 UIView 以外的任何类型扩展来轻松做到这一点:

protocol TestsProtocol:UIView {
    func test()
}

class FooClass: TestsProtocol {

    func test() {

    }
}

所以这会导致编译错误

'TestsProtocol' requires that 'FooClass' inherit from 'UIView'