我最近發現了在Swift中創建相當於NS_OPTIONS
的方法,但是我無法從Objective-C/Swift項目中的Objective-C代碼中使用它們。是RawOptionSetType兼容Objective-C嗎?
下面是一個簡單的項目,我做的事:
ObjcObject.h & ObjcObject.m
typedef NS_OPTIONS(NSUInteger, MyObjcOption)
{
MyOptionNone = 0,
MyObjcOptionCase01 = 1 << 0,
MyObjcOptionCase02 = 1 << 1,
MyObjcOptionCaseAll = MyObjcOptionCase01 | MyObjcOptionCase02
};
@interface ObjcObject : NSObject
+ (void)printMyObjcOption:(MyObjcOption)option;
@end
@implementation ObjcObject
+ (void)printMyObjcOption:(MyObjcOption)option
{
if (option == 0)
NSLog(@"None");
if (option & MyObjcOptionCase01)
NSLog(@"MyObjcOptionCase01");
if (option & MyObjcOptionCase02)
NSLog(@"MyObjcOptionCase02");
}
@end
SwiftObject.swift
struct MySwiftOption: RawOptionSetType, BooleanType {
private var value: UInt = 0
var rawValue: UInt { return self.value }
init(_ value: UInt) { self.value = value }
init(rawValue value: UInt) { self.value = value }
init(nilLiteral:()) { self.value = 0 }
var boolValue: Bool { return value != 0 }
static var allZeros: MySwiftOption { return self(0) }
static var None: MySwiftOption { return self(0) }
static var All: MySwiftOption { return self.Case01 | self.Case02 }
static var Case01: MySwiftOption { return self(1 << 0) }
static var Case02: MySwiftOption { return self(1 << 1) }
}
public class SwiftObject: NSObject {
class func printMySwiftOption(option: MySwiftOption) {
if option.rawValue == 0 {
println("None")
}
if option & MySwiftOption.Case01 {
println(".Case01")
}
if option & MySwiftOption.Case02 {
println(".Case02")
}
}
class func sayHello() {
println("Hello")
}
}
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
MyObjcOption objcOption = MyObjcOptionCase02;
[ObjcObject printMyObjcOption:objcOption];
[SwiftObject sayHello];
// MySwiftOption swiftOption = MySwiftOptionCase02; // Error: Use of undeclared identifier 'MySwiftOption'
// [SwiftObject printMySwiftOption:swiftOption];
return YES;
}
在Objective-C代碼中,我總是得到一個錯誤Use of undeclared identifier 'MySwiftOption'
。
這是一個已知的問題嗎?有沒有解決方法?
您是否添加了橋接頭文件? –
需要我嗎?我認爲我不需要它:我不會將Objective-C導入Swift。但是我導入了'* -Swift.h'文件。 '[SwiftObject sayHello];'工作正常。 –