5

I use J2objc to translate Java to Objective-C. This code I use with a bridging header to make it available in Swift. Here is a Java Enum I translated:

public enum BTestType {

  Type1, Type2, Type3;

}

In Objective-C I get the following header file (I skip the module file):

#ifndef _BISBTestType_H_
#define _BISBTestType_H_

#include "J2ObjC_header.h"
#include "java/lang/Enum.h"

typedef NS_ENUM(NSUInteger, BISBTestType) {
  BISBTestType_Type1 = 0,
  BISBTestType_Type2 = 1,
  BISBTestType_Type3 = 2,
};

@interface BISBTestTypeEnum : JavaLangEnum < NSCopying >

#pragma mark Package-Private

+ (IOSObjectArray *)values;
FOUNDATION_EXPORT IOSObjectArray *BISBTestTypeEnum_values();

+ (BISBTestTypeEnum *)valueOfWithNSString:(NSString *)name;
FOUNDATION_EXPORT BISBTestTypeEnum *BISBTestTypeEnum_valueOfWithNSString_(NSString *name);

- (id)copyWithZone:(NSZone *)zone;

@end

J2OBJC_STATIC_INIT(BISBTestTypeEnum)

FOUNDATION_EXPORT BISBTestTypeEnum *BISBTestTypeEnum_values_[];

#define BISBTestTypeEnum_Type1 BISBTestTypeEnum_values_[BISBTestType_Type1]
J2OBJC_ENUM_CONSTANT_GETTER(BISBTestTypeEnum, Type1)

#define BISBTestTypeEnum_Type2 BISBTestTypeEnum_values_[BISBTestType_Type2]
J2OBJC_ENUM_CONSTANT_GETTER(BISBTestTypeEnum, Type2)

#define BISBTestTypeEnum_Type3 BISBTestTypeEnum_values_[BISBTestType_Type3]
J2OBJC_ENUM_CONSTANT_GETTER(BISBTestTypeEnum, Type3)

J2OBJC_TYPE_LITERAL_HEADER(BISBTestTypeEnum)

typedef BISBTestTypeEnum BISTestTypeEnum;

#endif // _BISBTestType_H_

To access an enum in Swift I had to call the following:

 var r:BISBTestTypeEnum = BISBTestTypeEnum.values().objectAtIndex(BISBTestType.Type1.rawValue) as! BISBTestTypeEnum

Is there a simpler way of accessing the objective-c enums in Swift?

Michael
  • 32,527
  • 49
  • 210
  • 370

3 Answers3

2

There is a more simple way of doing this. Add the --static-accessor-methods flag and then you can access like:

var r:BISBTestTypeEnum = BISBTestTypeEnum.Type1()
0

For a simpler way of accessing the enum you could extend the the BISBTestTypeEnum class and implement a convenience class method:

extension BISBTestTypeEnum {
    class func withValue(value: BISBTestType) -> BISBTestTypeEnum {
        return BISBTestTypeEnum.values().objectAtIndex(value.rawValue) as! BISBTestTypeEnum
    }
}

And then you can use:

var r = BISBTestTypeEnum.withValue(BISBTestType.Type1)
marius
  • 2,077
  • 2
  • 16
  • 15
-1

It appears that you can use the method BISBTestTypeEnum_get_Type2() (derived from the J2OBJC_ENUM_CONSTANT_GETTER(BISBTestTypeEnum, Type2) macro), but though this passes compilation it fails at link time.

SureshKS
  • 49
  • 1
  • 3