【问题标题】:How to pass swift enum with @objc tag如何使用 @objc 标签传递 swift 枚举
【发布时间】:2014-07-31 04:33:07
【问题描述】:

我需要定义一个可以在使用某些 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 标签声明和传递我的枚举?

【问题讨论】:

  • 看我的回答。我很确定您的问题出在其他地方。

标签: ios enums swift


【解决方案1】:

Apple 今天刚刚宣布 Swift 1.2(包含在 xcode 6.3 中)将支持将枚举暴露给 Objective-c

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

【讨论】:

  • 供参考:这似乎仅适用于 Int 类型的枚举。将@objc 应用于 String 类型的枚举会产生以下编译错误:“'@objc' enum raw type 'String' is not an integer type。”
  • objc(和许多其他语言)仅支持整数中的枚举。 swift 在这方面是独一无二的
  • 在 Swift 2.0 中不起作用。 Swift ENUM 在 ObjC 中不可见
  • 确保你的枚举是 Int 类型并且像上面的例子一样标记为@objc
  • 它必须是 Int 继承自的类型,因为 obj-c / c 枚举类型表示与 Swift 不同。
【解决方案2】:

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

【讨论】:

  • 对,我的代码是纯 swift 的,但是它崩溃了,这与我在这里的另一个问题有关:stackoverflow.com/questions/24137090/…
  • 你应该离开你的编辑,你的问题完美地回答了我的问题,但正如你所说,我的代码是纯 Swift 的。我认为崩溃是因为我没有在它前面加上 @objc 标签。但听起来我错了。
  • @Dimillian77 抱歉,我做了无效的编辑,不得不重新编写。
  • 当然,除非您需要协议的可选值...非常烦人...哦,好吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多