[英]How to pass swift enum with @objc tag
我需要定义一个可以在使用某种Objective-c类型的类中调用的协议
但这样做不起作用:
enum NewsCellActionType: Int {
case Vote = 0
case Comments
case Time
}
@objc protocol NewsCellDelegate {
func newsCellDidSelectButton(cell: NewsCell, actionType: NewsCellActionType)
}
你得到他的错误
Swift enums cannot be represented in Objective-C
如果我没有将@objc标记放在我的协议上,那么只要它在一个采用协议并从Objective-C类型类(如UIViewController)继承的类中调用它就会崩溃应用程序。
所以我的问题是,我应该如何使用@objc标签声明并传递我的枚举?
Apple今天宣布,Swift 1.2(包含在xcode 6.3中)将支持将enum暴露给objective-c
Swift枚举与Obj-C(或C)枚举非常不同,它们不能直接传递给Obj-C。
作为解决方法,您可以使用Int
参数声明您的方法。
func newsCellDidSelectButton(cell: NewsCell, actionType: Int)
并将其作为NewsCellActionType.Vote.toRaw()
传递给它。 您将无法访问Obj-C中的枚举名称,这会使代码更加困难。
更好的解决方案可能是在Obj-C中实现枚举(例如,在您的briding header中),因为它将在Swift中自动访问,并且可以将其作为参数传递。
编辑
只需将@objc
用于Obj-C类就不需要添加它。 如果您的代码是纯Swift,则可以使用枚举而不会出现问题,请参阅以下示例作为证明:
enum NewsCellActionType : Int {
case Vote = 0
case Comments
case Time
}
protocol NewsCellDelegate {
func newsCellDidSelectButton(cell: UITableViewCell?, actionType: NewsCellActionType )
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, NewsCellDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
test()
return true;
}
func newsCellDidSelectButton(cell: UITableViewCell?, actionType: NewsCellActionType) {
println(actionType.toRaw());
}
func test() {
self.newsCellDidSelectButton(nil, actionType: NewsCellActionType.Vote)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.