Check existence of global function in Swift

谁说我不能喝 提交于 2019-12-07 01:35:49

问题


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


回答1:


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.




回答2:


No, it's not possible in Swift.

Even respondsToSelector uses the Obj-C runtime and can be used only for functions available in Obj-C.



来源:https://stackoverflow.com/questions/38353450/check-existence-of-global-function-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!