Search code examples
objective-cswiftenumsobjc-bridging-header

enum defined in Objc > Declared in Swift > to be used in Objc


I have a situation. I would appreciated if anyone has a solution for this

  • I have an objC enum say Abc
  • I declare this in a swift class, say, MySwiftClass.swift as var abc : Abc!
  • I have created an instance of MySwiftClass (mySwiftClass) in another ObjC class (myObjC.m file)
  • In myObjC.m, I’m trying to access enum Abc as mySwiftClass.abc.

This is throwing an error - “Property ‘abc’ not found on object of type MySwiftClass *”. Basically the enum is not added as property in the “ProjectName-Swift.h” file.

What I believe is happening is that when I’m declaring the ObjC enum in Swift class, it is getting converted to a swift enum and hence I’m not able to access it in ObjC file.

Note: Marking the Swift class as @objc did not work.


Solution

  • Numeric Swift optionals cannot be represented in Objective-C, and thus will not be exposed to Objective-C. Declare abc to not be optional and it should be available from Objective-C.

    Consider this Objective-C enumeration:

    typedef NS_ENUM(NSInteger, Foo) {
        FooBar,
        FooBaz,
        FooQux
    };
    

    Then consider this Swift 3 class:

    class SomeObject: NSObject {
        var foo1: Foo  = .bar          // this is exposed to Objective-C
        var foo2: Foo! = .bar          // this is not
    }
    

    The non-optional, foo1, will be exposed to Objective-C, whereas the optional, foo2, will not.