Are public swift functions on ObjC objects dynamically or statically dispatched?

241 views Asked by At

Here's my example, let's say I have a custom UIView with a tap gesture recognizer that responds to this function:

func handleTap(tap: UITapGestureRecognizer) {
    println("Tap!")
}

I generally prefer these to be private, so I mark it as such but it doesn't work. An @objc or dynamic specifier is required, like so:

dynamic private func handleTap(tap: UITapGestureRecognizer) {
    println("Tap!")
}

This makes me believe that public functions are dynamic by default when added to an objective-c object. Is this the case? Please cite references if found.

2

There are 2 answers

0
gnasher729 On BEST ANSWER

The Swift compiler will try to prove that a call to a method can only end up with a single implementation. If it can prove this then it will use static and not dynamic dispatch. Use of the "final" or "private" keyword, and whole module optimisation, will help with this.

2
sbooth On

From Using Swift with Cocoa and Objective-C:

Requiring Dynamic Dispatch

While the @objc attribute exposes your Swift API to the Objective-C runtime, it does not guarantee dynamic dispatch of a property, method, subscript, or initializer. The Swift compiler may still devirtualize or inline member access to optimize the performance of your code, bypassing the Objective-C runtime. When you mark a member declaration with the dynamic modifier, access to that member is always dynamically dispatched. Because declarations marked with the dynamic modifier are dispatched using the Objective-C runtime, they’re implicitly marked with the @objc attribute.”