在Swift中使用选择器是否有类型安全的方法?

Bil*_*ill 23 selector type-safety swift

在大多数情况下,Swift在类型安全方面是对Objective-C的巨大改进.一个明显的例外是选择器.在Objective-C中,使用表达式@selector(notARealSelector:)会给出编译器警告.Swift等价物Selector("notARealSelector:")将始终编译但在运行时将失败.

是否有一种在Swift中使用选择器的类型安全方法,所以我可以使用需要它们的Objective-C API?

我的NSNotification应用程序中有很多观察者,并希望进行某种编译时检查,我不会在我的选择器中输入拼写错误.

编辑:具体用例是NSNotificationCenter.addObserver.

And*_*rew 4

类型安全选择器刚刚在 Xcode 7.3 beta 4 中发布:

let sel = #selector(insertSubview(_:aboveSubview:)) // sel has type
Run Code Online (Sandbox Code Playgroud)

Selector现在是一等公民,并带有一些不错的 Swift 编译器警告。如果需要,您仍然可以传入一个字符串:

let sel = Selector("propertyName")
Run Code Online (Sandbox Code Playgroud)

在这里查看更完整的答案:@selector() in Swift?

Xcode 发行说明:http://adcdownload.apple.com/Developer_Tools/Xcode_7.3_beta_4/Xcode_7.3_beta_4_Release_Notes.pdf