1

I'm trying to create an Objc class, with a property of an enum type, where the enum type is created in swift. After this, I want to use the Objc class in Swift.

(Swift)Enum:

import Foundation

@objc enum AffectsUnit:Int {
    case time
    case person
    case group
}

(Objc)class

#import "JSONModel.h"
#import "MyApp-Swift.h"
@interface AddPlayerToTime : JSONModel
@property (nonatomic) AffectsUnit affectsUnit;
@end

The Objc class has an empty method file.

So far, so good. No compiler warnings.

Since i also want to use my objc class in Swift. I need to import the class in my Bridging-Header.h.

#import "AddPlayerToTime.h"

Now my swift code can see the AddPlayerToTime class, but the project will no longer compile. The error I get is:

Unknown type name 'AffectsUnit'

I'm 99% sure it breaks because of circular reference. Since my swift code is importing AddPlayerToTime class and AddPlayerToTime is importing my swift code. But I do not know how to fix this. All post on this circular reference matter, seem to suggest using @class declaration. But since I'm trying to refer to an enum, not a class, this is not a solution for me.

Am I trying to accomplish something, that simple can't be done?

Edit1: Please note: I want as much code as possible, to remain on the Swift side.

user2408952
  • 2,011
  • 5
  • 24
  • 26
  • Looks like you can do the forward declaration of the enum, checkout this link if it works for you. https://stackoverflow.com/questions/946489/forward-declare-enum-in-objective-c/42009056#42009056 –  Jul 04 '18 at 16:37
  • This would be for Objc enum, to be visible in Swift, yes? Without importing a header in your Bridging-Header. What I'm trying to achieve is the opposite (Make Swift enum visible to Objc). – user2408952 Jul 05 '18 at 07:50

1 Answers1

1

You should be able to move the enum declation over to the Obj-C side and still have it visible to Swift, like this:

typedef NS_ENUM(NSInteger, AffectsUnit)
{
    AffectsUnitTime,
    AffectsUnitPerson,
    AffectsUnitGroup
};
Gereon
  • 17,258
  • 4
  • 42
  • 73
  • This does work. And yes, it is till visible to Swift. Any way of getting it to work, while still having the enum on the Swift side? Reason why I'm asking is because I'm trying to slowly migrate away from Obj-C and more towards Swift. I've updated my post. – user2408952 Jul 04 '18 at 17:28
  • I created my AddPlayerToTime class in swift instead. This let me keep the enum on the swift side and still be useable on both code sides. Will +1 since our solution did solve my compiler warning. – user2408952 Jul 04 '18 at 17:55
  • It's been a while since I moved an app over to Swift, but I recall having to move the enums last because of this exact problem. – Gereon Jul 04 '18 at 20:58
  • Yeah, makes sense. My logic was "Enum's seem like a nice place to start, since they are so easy and fast to recreate in swift". Guess that was a really bad call I made there. – user2408952 Jul 05 '18 at 07:52