Member-only story

Argument of ‘#selector’ refers to instance method ‘buttonTapped()’ that is not exposed to Objective-C WHY SWIFT WHY

A common error in Swift

Steven Curtis
3 min readApr 2, 2020
Image: Ryanbaker271

Difficulty: Beginner | Easy | Normal | Challenging (although the in-depth explanations are quite tricky, they can be skipped)

When you write Swift code that needs to be called from Objective-C you need to expose that code to Objective-C, and to do this we can prefix a function with @objc attribute.

The real-life example

A UITapGestureRecognizer

We can set up a UITapGestureRecognizer and then add it to a UIButton (called UIButton here):

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(buttonTapped))
myButton.addGestureRecognizer(tapGesture)

Now the #selector is the clue that we need to expose that function to Objective-C.

The simple solution to this is to prefix a function with @objc to make it available, that is make an Objective-C thunk.

To break this down; when you mark a function @objc that creates the appropriate Objective-C selector and name that can be called by the Objective-C runtime.

--

--

No responses yet