如何通过@objc标签传递快速枚举

我需要定义一个可以在一个使用Objective-ctypes的类中调用的协议

但是这样做不起作用:

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)inheritance的协议。

所以我的问题是,我应该如何声明并通过@objc标签传递我的枚举?

Swift枚举与Obj-C(或C)枚举非常不同,不能直接传递给Obj-C。

作为一种解决方法,您可以使用Int参数声明您的方法。

 func newsCellDidSelectButton(cell: NewsCell, actionType: Int) 

并将其作为NewsCellActionType.Vote.toRaw()传递。 您将无法从Obj-C访问枚举名称,这会使代码变得更加困难。

一个更好的解决scheme可能是在Obj-C中实现枚举(例如,在你的briding头文件中),因为那样它将在Swift中被自动访问,并且可以将它作为parameter passing。

编辑

不需要添加@objc只是将它用于Obj-C类。 如果你的代码是纯粹的Swift,你可以使用枚举没有问题,请看下面的例子作为certificate:

 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) } } 

苹果公司今天刚刚宣布,Swift 1.2(包含在xcode 6.3中)将支持将枚举展示给objective-c

https://developer.apple.com/swift/blog/

在这里输入图像说明