Swift 闭包作为 AnyObject [英] Swift closure as AnyObject

查看:65
本文介绍了Swift 闭包作为 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屋!

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