检查Swift中是否存在全局函数 [英] Check existence of global function in Swift

查看:142
本文介绍了检查Swift中是否存在全局函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检测是否定义了某些全局函数(非类方法)(在iOS中)?像类中的 respondsToSelector ...

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

推荐答案

Swift目前的确如此不支持查找全局函数。

Swift currently does not support looking up global functions.

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

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


  • 使用弱链接符号

  • 动态链接器API: dlopen

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

如果可以找到符号,则动态检查(在运行时)。

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

这是一个检查 UIGraphicsBeginImageContextWithOptions (iOS 4引入)的示例:

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;
}

这是相同的检查,使用 dlsym

Here's the same check, using dlsym:

#import <dlfcn.h>

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

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

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

这篇关于检查Swift中是否存在全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆