2

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
4
  • Maybe, but from my own (limited) working with Objective-C and Objective-C++ and Swift: no. (But as said, "maybe", I may be wrong.) Commented Mar 15, 2023 at 0:23
  • 1
    NS_SWIFT_UNAVAILABLE? developer.apple.com/documentation/swift/… Commented Mar 15, 2023 at 0:57
  • Try this stackoverflow.com/a/33215044/1934750 Commented Mar 15, 2023 at 6:41
  • @Rob NS_SWIFT_UNAVAILABLE may work for hiding properties and methods, but I have to expose my C++ object as a property on the wrapper object, which means either forward-declaring its type or importing its header, both of which cause a compiler error. See the edit to the question. Commented Mar 15, 2023 at 16:49

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.