When Worlds Collide: How to call complex Objective-C selectors from Swift

When developing in Swift, you will eventually need to interact with Objective-C APIs. Most of the time this is fine, and fairly straightforward to do using #selector.

However, every once in a while you will need to invoke an Objective-C selector that you did not write (usually when the selector is part of the iOS or macOS SDK), does not have a unique signature, or is just pretty hard to figure out.

This article put out by Big Nerd Ranch’s Mark Dalrymple is an excellent rundown of how to properly invoke Objective-C selectors from Swift. He even covers really hairy signatures that may be very difficult to come up with on your own at first glance.

Big Nerd Ranch — Hannibal #selector

The selector is key to Objective-C’s dynamic runtime nature. It’s just a name that’s used, at runtime, as a key into a dictionary of function pointers. Whenever you send a message to an Objective-C object, you’re actually using a selector to look up a function to call. Sometimes selectors bubble up in Cocoa/CocoaTouch API, and you will need to deal with them in Swift.