简体   繁体   中英

Extend a Class that conforms a protocol?

How can I make an extension of a class that implements a protocol ?

Something like that :

protocol proto {
    func hey()
}

and a class that conforms to proto :

Class MyClass: UIViewController, proto {
     func hey() {
         print("Hey!")
     }
}

and then an extension of that class that would look like :

extension UIViewController where Self:proto {
     func test() {
         print("I'm extended!")
     }
}

So that I can call self.test() in MyClass .

Thanks.

You can just extend protocol, not the type. Please, try the following:

protocol proto {
    func hey()
}

class MyClass: UIViewController, proto {
    func hey() {
        print("Hey!")
    }

    func test2() {
        self.test()
    }
}

extension proto where Self: UIViewController {
    func test() {
        print("I'm extended!")
    }
}

First, you have to declare test method in proto so that MyClass knows it implements this method.

protocol proto {
    func hey()
    func test()
}

Also you have to "reverse" the statements in the protocol extension:

extension proto where Self : UIViewController {
    func test() {
        print("I'm extended!")
    }
}

After that, MyClass is magically extended and you can call test method on it:

class MyClass: UIViewController, proto {

    override func viewDidLoad() {
        super.viewDidLoad()
        test()
    }
}

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