如何通过带有@objc标签的swift枚举 [英] How to pass swift enum with @objc tag

查看:107
本文介绍了如何通过带有@objc标签的swift枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to define a protocol which can be called in a class that use some Objective-c type

但是这样做不起作用:

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

If I don't put the @objc tag on my protocol it'll crash the app as soon as it's called in a class which adopt the protocol AND inherit from an Objective-C type class (like a UIViewController).

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

So my question is, how should I declare and pass my enum with the @objc tag?

推荐答案

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

Swift enums are very different from Obj-C (or C) enums and they can't be passed directly to Obj-C.

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

As a workaround, you can declare your method with an Int parameter.

func newsCellDidSelectButton(cell: NewsCell, actionType: Int)

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

and pass it as NewsCellActionType.Vote.toRaw(). You won't be able to access the enum names from Obj-C though and it makes the code much more difficult.

更好的解决方案可能是实现枚举Obj-C(例如,在你的标题中),因为它会在Swift中自动访问,并且可以作为参数传递。

A better solution might be to implement the enum in Obj-C (for example, in your briding header) because then it will be automatically accessible in Swift and it will be possible to pass it as a parameter.

编辑

只需将 @objc 添加到Obj- C类。如果你的代码是纯Swift,你可以使用枚举没有问题,请参见以下示例作为证明:

It is not required to add @objc simply to use it for an Obj-C class. If your code is pure Swift, you can use enums without problems, see the following example as a proof:

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

这篇关于如何通过带有@objc标签的swift枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆