5

I have a Swift enum defined like this:

@objc enum SomeEnum: Int {
  case one, two
}

I can use SomeEnum in Objetive-C files normally, but when I want to declare a property in header file like this:

@property (nonatomic, assign) SomeEnum someEnum;

Compiler gives error message Unknown type name 'SomeEnum'. What's interesting I can create a property in private interface of the class. Also I tried cleaning the build folder, didn't help. File <module>-Swift.h is already imported in .pch file. Do you know what is the source of the problem?

Aleksander Grzyb
  • 749
  • 1
  • 6
  • 18
  • Include your error? –  Feb 24 '17 at 23:38
  • What is the exact error message? Did you import "YourProject-Swift.h"? – Martin R Feb 24 '17 at 23:38
  • Updated the question. – Aleksander Grzyb Feb 24 '17 at 23:42
  • 1
    Don't you have another error like **_error: failed to import bridging header '.../YourProject-Bridging-Header.h'_** when you find _Unknown type name 'SomeEnum'_? – OOPer Feb 25 '17 at 00:24
  • Yeah, I have, I didn't notice that. – Aleksander Grzyb Feb 25 '17 at 00:26
  • 2
    Generally, you should not put some dynamically generated header file into .pch . In your case, YourProject-Bridging-Header.h and your Objective-C class's .h file are getting mutually dependent and cannot be imported. The best and most steady solution is defining your enum in the Objective-C side. – OOPer Feb 25 '17 at 00:34
  • The answer to forward declaring a Swift enum in your Objective-C '.h' file is here: https://stackoverflow.com/a/42009056/102315 – Alper Mar 16 '18 at 07:59

1 Answers1

4

You can do the following trick:

ObjcClass.h

#import <Foundation/Foundation.h>

@interface ObjcClass : NSObject

@property (nonatomic, assign) SomeEnum someEnum;

@end

ObjcClass.m

#import "<module>-Swift.h" // The order is important here
#import "ObjcClass.h"

@implementation ObjcClass

@end

Downsides:

  1. You have to include <module>-Swift.h before classes using Swift enums.

  2. The other issue is if you decide to export the Objective-C class to Swift via Bridging header then you'll have a problem to resolve that enum.

If you can avoid mixing Swift and Objective-C in that way I suggest you do. Instead you can use Swift classes shared with Objective-C and then use forward declarations (i.e @class X) in headers.

The other option would be to move enum to Objective-C side as others suggested in comments.

Side note: <module>-Swift.h is better be included in implementation files, don't include it in headers ever to avoid any trouble and circular imports.

pronebird
  • 12,068
  • 5
  • 54
  • 82
  • 2
    The compiler complains that SomeEnum (or your custom swift enum) is not defined. I was looking for tips on how to include swift enums into objc header files. – Klajd Deda Sep 11 '17 at 17:11