簡體   English   中英

檢查Swift中是否存在全局函數

[英]Check existence of global function in Swift

是否可以檢測是否定義了某些全局函數 (非類方法)(在iOS中)? 像課堂上的respondsToSelector ...

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。

不,在Swift中不可能。

甚至respondsToSelector使用Obj-C運行時,並且只能用於Obj-C中可用的函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM