在Swift中用J2objc翻译的Access Enum

时间:2015-04-13 19:30:18

标签: java ios objective-c swift j2objc

我使用J2objc将Java转换为Objective-C。这个代码我用一个桥接头来使它在Swift中可用。这是我翻译的Java Enum:

public enum BTestType {

  Type1, Type2, Type3;

}

在Objective-C中,我得到以下头文件(我跳过模块文件):

#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_

要访问Swift中的枚举,我必须调用以下内容:

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

是否有更简单的方法可以访问Swift中的objective-c枚举?

3 个答案:

答案 0 :(得分:1)

有一种更简单的方法可以做到这一点。添加--static-accessor-methods标志,然后您可以访问:

var r:BISBTestTypeEnum = BISBTestTypeEnum.Type1()

答案 1 :(得分:0)

对于访问枚举的更简单方法,您可以扩展BISBTestTypeEnum类并实现一个便捷类方法:

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

然后你可以使用:

var r = BISBTestTypeEnum.withValue(BISBTestType.Type1)

答案 2 :(得分:-1)

看来您可以使用方法BISBTestTypeEnum_get_Type2()(从J2OBJC_ENUM_CONSTANT_GETTER(BISBTestTypeEnum, Type2)宏派生),但是虽然这会通过编译,但在链接时会失败。