Search code examples
c++swiftobjective-cobjective-c++

How can I hide part of an Objective-C class's interface from Swift?


I have an Xcode project that is a mix of Objective-C(++), C++, and Swift. Some of the Objective-C++ serves as a bridge between Swift and C++.

Say I have an Objective-C class with a public property whose type is a C++ class that I want to use from other parts of the Objective-C code. This will cause a compiler error if the header is imported in the Swift bridging header. Is there a way to hide part of the header of this Objective-C class from Swift?

EDIT: here's a sample header file to illustrate what I mean.

#import <Foundation/Foundation.h>

class MyCppType;

@interface SwiftCancelationToken : NSObject

//I need to expose this so Obj-C can interact with it
@property MyCppType *cppProperty;

-(void)doSomethingWithCppObject;

@end

Solution

  • Long story short - this is a mistake in the class API design. If you want to have a header compatible with Objective-C/Swift, it cannot expose any C++ stuff, such as C++ classes, templates, keywords, etc... There is only Swift - Objective-C interoperability (and sometimes C), but not Swift - Objective-C++ interoperability (there is however Swift - C++ interop project ongoing).

    On the other hand, you can technically put pre-processor, which may omit any C++ parts from the header, when the compiler-frontend is in another language mode with use of __cpluplus guards:

    #import <Foundation/Foundation.h>
    
    #ifdef __cplusplus
    class MyCppType;
    #endif
    
    @interface SwiftCancelationToken : NSObject
    
    #ifdef __cplusplus
    @property MyCppType *cppProperty;
    #endif
    
    -(void)doSomethingWithCppObject;
    
    @end