Search code examples
iosswiftprotocols

How to call a protocol's default function declared in a protocol extension?


I'm trying to call a protocol's default function that was declared in an extension:

protocol Tester {
    func printTest()
    }

extension Tester {
    func printTest() {
        print("XXXXTestXXXX")
    }
}

class TestController: UIViewController, Tester {

 let testing = Tester()// error here

    override func viewDidLoad() {
        super.viewDidLoad()

        testing.printTest()
    }

}

The error ''Tester' cannot be constructed because it has no accessible initializers' keeps appearing when I try to create an instance of the protocol. Whats the best way to use default functions in protocols?


Solution

  • You have to call the implementer, in your case it's TestController so :

    self.printTest() will work