Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check existence of global function in Swift

Is it possible to detect if some global function (not class method) is defined (in iOS)? Something like respondsToSelector in a class...

like image 805
JMI Avatar asked Jul 13 '16 13:07

JMI


1 Answers

Swift currently does not support looking up global functions.

For C functions (most global functions from Apple's frameworks are C functions) there are at least two ways:

  • using a weakly linked symbol
  • the dynamic linker API: dlopen

Both check dynamically (at runtime) if a symbol can be found.

Here's an example that checks if UIGraphicsBeginImageContextWithOptions (introduced with iOS 4) is available:

void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) __attribute__((weak));

static inline BOOL hasUIGraphicsBeginImageContextWithOptions() {
    return UIGraphicsBeginImageContextWithOptions != NULL;
}

Here's the same check, using dlsym:

#import <dlfcn.h>

static inline BOOL hasUIGraphicsBeginImageContextWithOptions() {
    return dlsym(RTLD_SELF, "UIGraphicsBeginImageContextWithOptions") != NULL;
}

The advantage of using dlsym is that you don't need a declaration and that it's easily portable to Swift.

like image 187
Nikolai Ruhe Avatar answered Oct 21 '22 13:10

Nikolai Ruhe