How to create constraint on protocol

你离开我真会死。 提交于 2021-02-11 10:58:52

问题


I tried to create protocol which can be only implemented by classes which inherit from UIView, what was my surprise when this code compiles without errors (in Swift 3.0):

protocol TestsProtocol {
    func test()
}

extension TestsProtocol where Self: UIView { }

class FooClass: TestsProtocol {

    func test() {

    }
}

We can see that FooClass don't inherit from UIView, using protocol extension I wan't to force that only classes which inherit from UIView can implement it. As far as I remember this would not compile in Swift 2.1


回答1:


You cannot do this in Swift. The extension syntax does something else:

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

now any class which implements TestsProtocol and is a UIView (or subclass) also has the useful() function.




回答2:


You can do that easily by limit protocol from be extendable from any type other than UIView :

protocol TestsProtocol:UIView {
    func test()
}

class FooClass: TestsProtocol {

    func test() {

    }
}

So this will cause compile error

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



来源:https://stackoverflow.com/questions/42120465/how-to-create-constraint-on-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!