Implement protocol default protocol implementation

I am trying to create a protocol that will be implemented by specific classes, and they should all implement as well UIScrollViewDelegate. I thought for my new protocol to implement the protocol UIScrollViewDelegate.

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

Since the protocol must 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 will be the right way to create an extended protocol implementation by default?

+4
source share
1 answer

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")
    }
}

MyProtocol2 UIScrollViewDelegate,

, :

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"
    }
}

, NSObject, , ,

anotherClass NSObjectProtocol

, UIScrollViewDelegate NSObjectProtocol, objective-C, NSObject.

, NSObject, NSObjectProtocol. .

+5

Source: https://habr.com/ru/post/1627960/


All Articles