检查 Swift 中是否存在全局函数

Check existence of global function in Swift

是否可以检测是否定义了某些 全局函数 (不是 class 方法)(在 iOS 中)? class...

中的 respondsToSelector

不,在 Swift 中不可能。

甚至 respondsToSelector 使用 Obj-C 运行时并且只能用于 Obj-C 中可用的函数。

Swift目前不支持查找全局函数。

对于 C 函数(Apple 框架中的大多数全局函数都是 C 函数)至少有两种方法:

  • 使用弱链接符号
  • 动态链接器API:dlopen

两者都动态检查(在运行时)是否可以找到符号。

这是一个检查 UIGraphicsBeginImageContextWithOptions(与 iOS 4 一起引入)是否可用的示例:

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

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

这是相同的检查,使用 dlsym:

#import <dlfcn.h>

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

使用 dlsym 的优点是您不需要声明,并且可以轻松移植到 Swift。