Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Protocol Function from A Selector in Swift

I have a protocol that acts as a delegate between one view and another.

The protocol looks (something like) this:

protocol MyProtocol: class {
    func functionOne()
}

And the protocol is implemented in View2 with something like:

extension View2:MyProtocol {
    func functionOne() {
        print("Hello World"
    }
}

Now I want this method to be called by the target of a button in View1. Therefore in View1 I have a line:

myButton(self, action: #selector(delegate?.functionOne), forControlEvents: .TouchUpInside)

But the button line errors with "Use of unresolved identifier 'functionOne'", which is an error I haven't seen before in other questions.

Everything works if I make a functionTwo in View1 and set the target to functionTwo, and then implement functionTwo by directly calling delegate?.functionOne. But that seems very inelegant.

like image 407
Kenneth Avatar asked Jul 16 '16 02:07

Kenneth


1 Answers

@objc
protocol MyProtocol: class {
    func functionOne()
}


button.addTarget(self, action: #selector(MyProtocol.functionOne), for: .touchUpInside)

The above syntax doesn't care where the protocol is implemented. It only cares about the name of the function and its signature. Because of this behaviour, we say MyProtocol.functionOne and that tells it enough. Some class conforms to that and implements a function with that signature and name.

like image 93
Brandon Avatar answered Sep 30 '22 01:09

Brandon