Compatible with RawOptionSetType Objective-C?

I recently discovered a way to create an equivalent NS_OPTIONSin Swift, however I cannot use them from Objective-C code in an Objective-C / Swift project.

Here is an example project that I did:

ObjcObject.h and 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;
}

In Objective-C code, I always get an error Use of undeclared identifier 'MySwiftOption'.

Is this a known issue? Is there any workaround?

+4
source share
1 answer

You cannot expose structures from Swift to ObjectiveC. Actually, look at the -Swift.h file to find out what you can get from Objective. You will not find MySwiftOptions there.

- , @objc, Objective-C. Swift, :

Generics Tuples,

, Swift,

, Swift,

, Swift,

, Swift,

, Swift,

Swift ,

, , .

Swift Cocoa Objective-C Apple.

+1

All Articles