如何使用@objc标记传递swift枚举

Dim*_*ian 32 enums ios swift

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

但这样做不起作用:

enum NewsCellActionType: Int {
    case Vote = 0
    case Comments
    case Time
}

@objc protocol NewsCellDelegate {
    func newsCellDidSelectButton(cell: NewsCell, actionType: NewsCellActionType)
}
Run Code Online (Sandbox Code Playgroud)

你得到他的错误

Swift enums cannot be represented in Objective-C
Run Code Online (Sandbox Code Playgroud)

如果我没有将@objc标记放在我的协议上,那么只要在采用协议并从Objective-C类型类(如UIViewController)继承的类中调用它,它就会崩溃应用程序.

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

Ore*_*ren 52

Apple今天宣布,Swift 1.2(包含在xcode 6.3中)将支持将enum暴露给objective-c

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

在此输入图像描述

  • 有关信息:这似乎仅适用于Int类型的枚举.将@objc应用于String类型的枚举会产生以下编译错误:"'@ objc'enum raw type'String'不是整数类型." (2认同)
  • 在Swift 2.0中不起作用。Swift ENUM在ObjC中不可见 (2认同)

Sul*_*han 7

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

作为解决方法,您可以使用Int参数声明方法.

func newsCellDidSelectButton(cell: NewsCell, actionType: Int)
Run Code Online (Sandbox Code Playgroud)

并传递给它NewsCellActionType.Vote.toRaw().您将无法访问Obj-C中的枚举名称,这会使代码更加困难.

更好的解决方案可能是在Obj-C中实现枚举(例如,在您的briding标头中),因为它将在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)
    }
}
Run Code Online (Sandbox Code Playgroud)