简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM