Defining a reference class from a prefix header in swift

I am adding quick code to an existing Objective-C project. I am having problems referencing a definition from an existing prefix header.

I have a MyClass class defined in Objective-C with .h:

@interface MyClass +(instancetype)myClass; -(void)doStuff; @end 

And .m:

 @implementation MyClass + (instancetype) myClass { // More to it than this, but this illustrates the setup return [[MyClass alloc] init]; } - (void)doStuff { // Do something interesting } @end 

The prefix header MyProj-Prefix.pch contains:

 #define MYCLASS MyClass #define SOMEVAR @"Hello" 

I created a bridge header that contains:

 #import "MyProj-Prefix.pch" 

The project contains Objective-C code that uses a class definition, for example

 [[MYCLASS myClass] doStuff]; 

I would like to reflect this in my new quick code. I see and refer to a specific variable, but a specific class is not displayed. eg.

 let someStr = SOMEVAR // This compiles MYCLASS.myClass.doStuff() // MYCLASS isn't visible 

Any pointers on how to achieve this? I'm not even sure if this is possible quickly.

+5
source share
1 answer

This problem will exist even if #define MYCLASS MyClass was in any other header, not necessarily in the prefix header. This is because preprocessor directives are usually not imported into Swift. However, simple macros are imported if they can be mapped to global constants, which is possible for SOMEVAR , but not MYCLASS . See https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-ID17 .

You can use typealias in Swift in the global scope:

 typealias MYCLASS = MyClass 

Of course, type modifications must be changed if MYCLASS been redefined in the header.

This approach is not very useful, unfortunately, if the definition of MYCLASS changes depending on where / how the code is generated. However, since the code needs to know a little about the behavior common to various classes, which can be defined as MYCLASS , it is possible that protocols can be used here.

UPDATE: Thinking about playing a little more with him and reading some other posts, for example. Using obj-c typedef in Swift , here is the best solution I think. With this approach, you do not need to change your Swift code if MYCLASS is rec #define d in Objective-C.

Somewhere in your Objective-C code, for example. in the heading add

 typedef MYCLASS * _MYCLASS; 

which then allows you to do the following in Swift:

 _MYCLASS.myClass().doStuff() 

If you really insist on using MYCLASS in Swift for any reason, adding typealias MYCLASS = _MYCLASS to your Swift code will do the trick.

+1
source

Source: https://habr.com/ru/post/1273709/


All Articles