Kenneth Kenneth - 4 months ago 12
iOS Question

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.

Answer
@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.

Comments