Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default implementation of protocol implementing protocol

I'm trying to create a protocol that would be implemented by certain classes, all of them should also implement UIScrollViewDelegate. What I thought of is for my new protocol to implement the protocol UIScrollViewDelegate.

protocol MyProtocol: UIScrollViewDelegate {
    var myVar: NSString { get }
    func myMethod()
}

As the protocol should have its default implementation I also created an extension for this protocol.

extension MyProtocol {
    func myMethod() {
        print("I'm printing")
    }

    func scrollViewDidScroll(scrollView: UIScrollView) {
        print("I'm scrollin")
    }
}

It compiles, but does not work. What am I doing wrong and what would be the right way to create a default implementation of expanded protocol?

like image 220
Eryk Sajur Avatar asked Feb 09 '16 12:02

Eryk Sajur


1 Answers

What you want to do is the following:

protocol MyProtocol{
    var myVar: NSString { get }
    func myMethod()
}

protocol MyProtocol2{
    var myVar2: NSString { get }
    func myMethod2()
}

extension MyProtocol where Self: MyProtocol2 {
    func myMethod() {
        print("I'm printing ")
    }
}

class anotherClass: MyProtocol, MyProtocol2 {
    var myVar: NSString {
        return "Yo"
    }

    var myVar2: NSString {
        return "Yo2"
    }

    func myMethod2() {
        print("I'm printing in myMethod2")
    }
}

In the above code MyProtocol2 is equivalent to your UIScrollViewDelegate,

hence what you will do is:

protocol MyProtocol{
    var myVar: NSString { get }
    func myMethod()
}

extension MyProtocol where Self: UIScrollViewDelegate {
    func myMethod() {
        print("I'm printing")
    }
}

class anotherClass: NSObject, MyProtocol, UIScrollViewDelegate {
    var myVar: NSString {
        return "Yo"
    }
}

Notice that another class subclasses NSObject, this is because if you do not do so, you will get the error

anotherClass does not conform to protocol NSObjectProtocol

This error is because UIScrollViewDelegate itself is defined to be extending NSObjectProtocol which is an objective-C protocol implemented by NSObject.

So make your class inherit from NSObject to conform to the NSObjectProtocol. Vanilla Swift classes do not.

like image 137
Sumeet Avatar answered Sep 28 '22 14:09

Sumeet