Tip on using Objective-C methods inside Swift protocol extension


I love building reusable components based on protocols, that can provide additional functionality for adopters. And sometimes I want to add for example gestures on UIView subclasses adopters.

So I have to add method that adds gesture recognizer and sets it target and action to handle it. Remember that action property is Selector and the method we referring in the selector must be available to Objective-C, thus marked with @objc modifier. But when we add the modifier we have the following error:

So for now it seems that there is no way to solve the puzzle. But actually there is the solution I found.


What we are to do is to create Objective-C class that will act like a proxy, calling closures we provided on initialization when particular method is called. So that is the class:

Now we have to integrate it in our extension somehow. We all know that we cannot have stored properties there, but we also all know that we can use ObjC API to do it.

So there is the complete extension.

Notice how we set target and action on line 49. Also notice how we initially set proxy object in its getter as we don’t have any other entry point to do this.

So now all I have to do in my views to make then be refreshable by swipe is to call recognizer adding and implement my refresh logic.

This is simple example of how you can solve the problem stated above.

Hope I help someone! Thank you for reading.




iOS-Developer from Russia

Love podcasts or audiobooks? Learn on the go with our new app.

New in SwiftUI 3: TimelineView in SwiftUI 3 and iOS 15

The New SwiftUI 4 Features for iOS 16

Implementing Multiple Window Support in iPadOS

The Swift Summary in April 2022

Architectures comparing for SwiftUI

UI Layout in IOS: Storyboard vs Programmatic

Jailbreak iOS 13.7 to install Cydia

New in SwiftUI 4: Resizable Bottom Sheet

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Isa Aliev

Isa Aliev

iOS-Developer from Russia

More from Medium

Equal Stacks Swift HackerRank Solution

SOLID Principles in Swift — Liskov Substitution Principle

Setup iOS Automation Test using Robot Framework and Appium

Combine Core Image Filters and CIDetector to Build Useful iOS Photo & Video Processing Apps