How to reference Swift enum in Objective-C Header

前端 未结 7 2173
星月不相逢
星月不相逢 2021-01-31 19:38

Is there a way to reference a Swift enum from an Objective-C header? If you want to see Swift classes in the Objective-C header you can use

@objc class Foo
         


        
7条回答
  •  执念已碎
    2021-01-31 20:12

    As far as I can tell, raf's answer is still correct. The cleanest solution is to simply leave your enum in an Objective-C file until you no longer need to access it from an Objective-C header. I wanted to offer another possible workaround, though.

    In my case I am gradually rewriting a large Objective-C project in Swift, and I don't mind an imperfect workaround if it allows me to rewrite more of my code in Swift. So I've settled on simply passing the enum to Objective-C as it's raw type, Int, or NSInteger to Objective-C. For example:

    - (void)doSomethingWithType:(NSInteger)rawType {
        if (rawType == ExampleTypeWhatever) {
            // Do something
        } // etc...
    }
    

    When I call this method from Swift, all I have to do is pass the .rawType, instead of the actual enum value:

    objcObject.doSomething(withType: ExampleType.whatever.rawValue)
    

    This keeps things fairly simple on both sides, and it'll be easy to update once doSomethingWithType: is eventually rewritten in Swift.

提交回复
热议问题