Swift 闭包作为 AnyObject [英] Swift closure as AnyObject
问题描述
我正在尝试使用此方法:class_addMethod()
在 Obj-c 中是这样使用的:
Im trying to use this method: class_addMethod()
which in Obj-c is used like this:
class_addMethod([self class], @selector(eventHandler), imp_implementationWithBlock(handler), "v@:");
我在 Swift 中是这样使用它的:
And Im using it like this in Swift:
class_addMethod(NSClassFromString("UIBarButtonItem"), "handler", imp_implementationWithBlock(handler), "v@:")
正如您可能已经想到的那样,它是 UIBarButtonItem
的扩展.
It is an extension for UIBarButtonItem
as you might have figured out.
imp_implementationWithBlock
接受 AnyObject!
如何将 ()->()
转换为 AnyObject
?
How can I cast ()->()
into AnyObject
?
我试过这样转换:handler as AnyObject
但它给了我一个错误说:()->() 不符合协议AnyObject"代码>
I've tried to cast it like this: handler as AnyObject
but it gives me an error saying: ()->() does not conform to protocol 'AnyObject'
推荐答案
如何将
()->()
转换为AnyObject
?
警告:此答案包括 Swift 中未记录和不安全的功能.我怀疑这是否通过了 AppStore 审核.
Warning: This answer includes undocumented and unsafe feature in Swift. I doubt this passes AppStore review.
let f: ()->() = {
println("test")
}
let imp = imp_implementationWithBlock(
unsafeBitCast(
f as @objc_block ()->(),
AnyObject.self
)
)
这篇关于Swift 闭包作为 AnyObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!