Is it possible to use Swift's Enum in Obj-C?
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];
}
To expand on the selected answer...
It is possible to share Swift style enums between Swift and Objective-C using NS_ENUM()
.
They just need to be defined in an Objective-C context using NS_ENUM()
and they are made available using Swift dot notation.
From the Using Swift with Cocoa and Objective-C
Swift imports as a Swift enumeration any C-style enumeration marked with the
NS_ENUM
macro. This means that the prefixes to enumeration value names are truncated when they are imported into Swift, whether they’re defined in system frameworks or in custom code.
Objective-C
typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
UITableViewCellStyleDefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
UITableViewCellStyleSubtitle
};
Swift
let cellStyle: UITableViewCellStyle = .Default
From the Using Swift with Cocoa and Objective-C guide:
A Swift class or protocol must be marked with the @objc attribute to be accessible and usable in Objective-C. [...]
You’ll have access to anything within a class or protocol that’s marked with the @objc attribute as long as it’s compatible with Objective-C. This excludes Swift-only features such as those listed here:
Generics Tuples / Enumerations defined in Swift / Structures defined in Swift / Top-level functions defined in Swift / Global variables defined in Swift / Typealiases defined in Swift / Swift-style variadics / Nested types / Curried functions
So, no, you can't use a Swift enum in an Objective-C class.