在Swift中用J2objc翻译的Access Enum

con*_*ile 5 java objective-c ios swift j2objc

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

public enum BTestType {

  Type1, Type2, Type3;

}
Run Code Online (Sandbox Code Playgroud)

在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_
Run Code Online (Sandbox Code Playgroud)

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

 var r:BISBTestTypeEnum = BISBTestTypeEnum.values().objectAtIndex(BISBTestType.Type1.rawValue) as! BISBTestTypeEnum
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法来访问Swift中的objective-c枚举?

mar*_*ius 0

为了更简单地访问枚举,您可以扩展该类BISBTestTypeEnum并实现一个方便的类方法:

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

然后你可以使用:

var r = BISBTestTypeEnum.withValue(BISBTestType.Type1)
Run Code Online (Sandbox Code Playgroud)