Robert
Robert

Reputation: 3880

How to create constraint on protocol

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

Upvotes: 2

Views: 1880

Answers (2)

Saeed Alasiry
Saeed Alasiry

Reputation: 342

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'

Upvotes: 1

simonWasHere
simonWasHere

Reputation: 1340

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.

Upvotes: 2

Related Questions