我正在寻找一种方法来比较指向c函数的指针.例如.:
let firstHandler = NSGetUncaughtExceptionHandler() NSSetUncaughtExceptionHandler(onUncaughtException) let secondHandler = NSGetUncaughtExceptionHandler() if firstHandler == secondHandler { debugPrint("equal") }
更新==,也不是===有效
在目标C中,我可以表达如下:
NSUncaughtExceptionHandler *firstHandler = NSGetUncaughtExceptionHandler(); NSSetUncaughtExceptionHandler(onUncaughtException); NSUncaughtExceptionHandler *secondHandler = NSGetUncaughtExceptionHandler(); if (firstHandler == secondHandler) { NSLog(@"equal"); }
提前致谢
通常,您无法在Swift中比较函数的相等性.
但是,NSSetUncaughtExceptionHandler返回一个
但是,NSSetUncaughtExceptionHandler返回一个
(@convention(c) (NSException) -> Swift.Void)?
即(可选的)C兼容功能,并且这样的功能可以是
强制转换为(可选)原始指针
unsafeBitCast:
let ptr1 = unsafeBitCast(firstHandler,to: Optional<UnsafeRawPointer>.self) let ptr2 = unsafeBitCast(secondHandler,to: Optional<UnsafeRawPointer>.self)
然后可以比较平等
if ptr1 == ptr2 {.. }
一个独立的例子:
func exceptionHandler1(exception : NSException) { } func exceptionHandler2(exception : NSException) { } NSSetUncaughtExceptionHandler(exceptionHandler1) let firstHandler = NSGetUncaughtExceptionHandler() NSSetUncaughtExceptionHandler(exceptionHandler2) let secondHandler = NSGetUncaughtExceptionHandler() let ptr1 = unsafeBitCast(firstHandler,to: Optional<UnsafeRawPointer>.self) print(ptr1 == ptr2) // false