#selector 与闭包不兼容?

Man*_*son 3 closures func selector swift

我试图用闭包来实现自定义函数。但它不受#selector.

下面是一个例子:

class Core: NSObject {

    static let shared:Core = Core.init()


    func button(viewController: UIViewController, button: UIButton, title: String, color: UIColor, completion: () -> Void) {

        button.layer.cornerRadius = button.bounds.width / 2
        button.setTitle(title, for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = color
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.addTarget(viewController, action: #selector(completion()), for: .touchUpInside)
    }
}
Run Code Online (Sandbox Code Playgroud)

Xcode 给了我一个构建时间问题:

“#selector”的参数不引用“@objc”方法、属性或初始值设定项

Ale*_*ica 5

选择器是一个字符串,用于标识 Objective C 运行时中的方法、属性、初始值设定项。当您使用诸如 之类的表示法时#selector(SomeClass.SomeMethod(withParam:AndParam:),您是以编译器可以轻松解析并验证其正确性的格式指定选择器。但最终,这将只是被降低到C字符串,如:"SomeMethodwithParam:AndParam:"

本质上,每个类都有一个字典,它将选择器映射到实现它们的代码的函数指针。当使用选择器调用函数时,Objective C 运行时会在方法表中搜索相关类,并查找与给定选择器对应的方法实现。

这个过程无法使用闭包,根据定义,闭包是匿名的。因此,您只能使用选择器来引用在 Objective C 运行时注册的方法、属性、初始值设定项(@objc隐式或显式这样做)。