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?

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

my old Obj-C Code:

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

@interface SomeClass : NSObject

...

@end

my new Swift Code:

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

class SomeClass: NSObject
{
    ...
}

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

推荐答案

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
}

Shamelessly taken from the Swift Blog

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


In Objective-C this would look like

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

Swift相关问答推荐

是否有一个Kotlin等价的Swift s @ AddendableReport注释'

传递给SWIFT ResultBuilder的闭包中结果类型的对象

如何在SWIFT中使用DiscardingTaskGroup获得任务结果

如何将函数参数(字符串文字)标记为可本地化?

Swift ui 转换无法按预期工作

如何在设备(或常量)地址空间中创建缓冲区?

如何在 UITableView 中点击图片和标题

快速递归:函数与闭包

从 Int 到 String 的属性更改引发 SwiftUI 视图不更新

响应 UITextField (UIViewRepresentable) 中的特定按键

如何在 SwiftUI 的 fileImporter 中为 allowedContentTypes 设置 xcodeproj 类型?

如何获取 NSRunningApplication 的参数?

如何轻松删除领域中的所有对象

更改日期 Select 器的文本 colored颜色

快速在 LLDB 中使用 po

将强制向下转换视为可选将永远不会产生零

如何在 GCD 中停止 DispatchWorkItem?

如何从一个可观察的数组创建一个可观察的数组?

哪些版本的 Xcode 支持哪些版本的 Swift?

为什么枚举具有计算(computed)属性但在 Swift 中没有存储属性?