问题
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