Search code examples
iosobjective-cswiftenumsobjective-c-swift-bridge

Import Obj-C file which imports auto-generated Swift header


This is a partial duplicate of Import a file in bridging-header which imports Swift header but I encounter the same issue as Rich

But what about enums declared in Swift? :(

I am porting an Obj-C iPad app to the iPhone. However I am a Swift developer who would really rather not rewrite existing functionality; replacing the UI instead.

I created a new target for the iPhone version. In my bridging header I import an obj-c class that uses #import "ProjectName-Swift.h". Since this file is autogenerated it doesn't exist when I build this new target. The linked answer is to add a @class but the legacy code makes use of an enum which is now giving the error "Expected a type".

// File that I am currently importing
-(void)setSmileyType:(SmileyFace)type andDelegate:(id<NumberRatingDelegate>)delegate;
// This line now throws an error "Expected a type"

//File that was previously auto imported
@objc public enum SmileyFace: Int {

Solution

  • @objc enum in Swift is exposed as a C-enum in ProjectName-Swift.h . (Using a macro SWIFT_ENUM.)

    You can put something like this into your Objective-C header files which are using the Swift enum:

    typedef enum SmileyFace: NSInteger SmileyFace;
    

    (Same as the first part of the generated code with the macro SWIFT_ENUM.)