Andrew
Andrew

Reputation: 7883

Objective-C enum not recognized in Swift

I have a delegate method that passes an enum as an argument:

func gestureRecognizer(gestureRecognizer: JTTableViewGestureRecognizer!, commitEditingState state: JTTableViewCellEditingState, forRowAtIndexPath indexPath: NSIndexPath!) -> Void {
    //....
}

The enum is JTTableViewCellEditingState. It's implementation is in the same header file as the delegate method. It's as follows:

typedef enum {
    JTTableViewCellEditingStateMiddle,
    JTTableViewCellEditingStateLeft,
    JTTableViewCellEditingStateRight,
} JTTableViewCellEditingState;

Yet trying to reference a state, for example Left, gives an error:

if state == JTTableViewCellEditingState.Left {

'JTTableViewCellEditingState.Type' does not have a member named 'Left'

Trying to do it the old, Objective-C way, like some kind of peasant, gives me a different, more expected, error:

if state == JTTableViewCellEditingStateLeft {

Cannot invoke '==' with an argument list of type '(JTTableViewCellEditingState, JTTableViewCellEditingState)'

I'm wondering how I should overcome this issue? I believe referencing Objective-C enums has worked just fine in the past.

Upvotes: 1

Views: 1713

Answers (3)

mustafa
mustafa

Reputation: 15464

This type of enum decleration causes problems in swift. I had similar problem. My solution is to create a helper objective-c method that does comparison and use that method in swift whenever == is needed.

Other solution may be refactor that code if you can and convert it proper enum decleration in objective-c.

typedef NS_ENUM(NSInteger, MyEnum) {
    MyEnumValue1,
    MyEnumValue2
};

Upvotes: 3

rintaro
rintaro

Reputation: 51911

In my environment - Xcode Version 6.1.1 (6A2006):

typedef enum {
    JTTableViewCellEditingStateMiddle,
    JTTableViewCellEditingStateLeft,
    JTTableViewCellEditingStateRight,
} JTTableViewCellEditingState;

is exported to Swift as:

struct JTTableViewCellEditingState {
    init(_ value: UInt32)
    var value: UInt32
}
var JTTableViewCellEditingStateMiddle: JTTableViewCellEditingState { get }
var JTTableViewCellEditingStateLeft: JTTableViewCellEditingState { get }
var JTTableViewCellEditingStateRight: JTTableViewCellEditingState { get }

So, this should works:

func gestureRecognizer(gestureRecognizer: JTTableViewGestureRecognizer!, commitEditingState state: JTTableViewCellEditingState, forRowAtIndexPath indexPath: NSIndexPath!) -> Void {
    if state.value == JTTableViewCellEditingStateLeft.value {
        // ...
    }
}

Upvotes: 2

Jake Lin
Jake Lin

Reputation: 11494

Can you use NS_ENUM instead? And then try JTTableViewCellEditingState.JTTableViewCellEditingStateLeft or even .JTTableViewCellEditingStateLeft to access your enum. If you can't change it to NS_ENUM, please have a look at Using non NS_ENUM objective-C enum in swift

Upvotes: 2

Related Questions