从Swift 3开始,如何使用定义为Obj-C块的类型,以id *指针作为参数



我的Swift 3.0项目使用了一个Objective-C库,它将特定类型(AsyncBlock)定义为Obj-C块:

typedef BOOL (^AsyncBlock)(id __nullable * __nonnull context);

在Swift 3.0术语中,这应该转换为指向可选值的非可选指针,所以我认为我应该能够将AsyncBlock类型的变量分配给我的Swift 3项目中定义的闭包,如下所示(不包括桥接头和其他简短的细节):

func closure(_ context: UnsafeMutablePointer<Any?>) -> Bool { return true } var myClosureVariable: AsyncBlock = closure

编译器不同意:Cannot assign value of type '(UnsafeMutablePointer<Any?>) -> Bool' to type 'AsyncBlock' -我做错了什么?

Obj-C id通常映射到Swift 3.0 Any,但这里我们必须使用AnyObject(不确定为什么)。此外,我们需要使用AutoreleasingUnsafeMutablePointer而不是UnsafeMutablePointer(同样,不清楚原因)

如此:

func closure(_ context: AutoreleasingUnsafeMutablePointer<AnyObject?>) -> Bool { return true } var myClosureVariable: AsyncBlock = closure

相关内容

最新更新