是否可以在 Obj-C 中使用 Swift 的 Enum? [英] Is it possible to use Swift's Enum in Obj-C?

查看:9
本文介绍了是否可以在 Obj-C 中使用 Swift 的 Enum?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的一些 Obj-C 类转换为 Swift.而其他一些 Obj-C 类仍在该转换后的类中使用枚举.我在 Pre-Release Docs 中搜索过,但找不到,或者我错过了.有没有办法在 Obj-C 类中使用 Swift 枚举?或者这个问题的文档的链接?

I'm trying to convert some of my Obj-C class to Swift. And some other Obj-C classes still using enum in that converted class. I searched In the Pre-Release Docs and couldn't find it or maybe I missed it. Is there a way to use Swift enum in Obj-C Class? Or a link to the doc of this issue?

这就是我在旧的 Obj-C 代码和新的 Swift 代码中声明枚举的方式.

This is how I declared my enum in my old Obj-C code and new Swift code.

我的旧 Obj-C 代码:

my old Obj-C Code:

typedef NS_ENUM(NSInteger, SomeEnum)
{
    SomeEnumA,
    SomeEnumB,
    SomeEnumC
};

@interface SomeClass : NSObject

...

@end

我的新 Swift 代码:

my new Swift Code:

enum SomeEnum: NSInteger
{
    case A
    case B
    case C
};

class SomeClass: NSObject
{
    ...
}

更新:来自答案.它不能在 Swift 1.2 之前的版本中完成.但根据这个官方 Swift 博客.在随 XCode 6.3 一起发布的 Swift 1.2 中,您可以通过在 enum

Update: From the answers. It can't be done in Swift older version than 1.2. But according to this official Swift Blog. In Swift 1.2 that released along with XCode 6.3, You can use Swift Enum in Objective-C by adding @objc in front of enum

推荐答案

从 Swift 版本 1.2 (Xcode 6.3) 开始,您可以.只需在枚举声明前加上 @objc

As of Swift version 1.2 (Xcode 6.3) you can. Simply prefix the enum declaration with @objc

@objc enum Bear: Int {
    case Black, Grizzly, Polar
}

无耻地摘自 Swift 博客

注意:这不适用于字符串枚举或具有关联值的枚举.您的枚举需要绑定 Int

Note: This would not work for String enums or enums with associated values. Your enum will need to be Int-bound

<小时>

在 Objective-C 中,这看起来像


In Objective-C this would look like

Bear type = BearBlack;
switch (type) {
    case BearBlack:
    case BearGrizzly:
    case BearPolar:
       [self runLikeHell];
}

这篇关于是否可以在 Obj-C 中使用 Swift 的 Enum?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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