Can't compile a Swift package which is using an Objective-C package

Viewed 1767

I am trying to capsule native C++ code with an Objective-C module. This works fine. Next I am trying to use that module from Swift, but I am not able to use the Objective-C class from Swift code. I have tried build two separate modules or one module with two targets - same error "Use of unresolved identifier 'Bridge'" and also a warning, that the umbrella directory ../Objective-CCode/include is not found.

I guess that the bridging header between Objective-C and Swift is missing. In a mixed code environment this header is generated automatically, but not in the package management.

What is missing or what is my fault? I have attached a small example of my problem.

"Package.swift" Package description.

// swift-tools-version:5.1

import PackageDescription

let package = Package(
    name: "MixedExample",
    products: [
        .library(
            name: "MixedExample",
            targets: ["SwiftCode", "Objective-CCode"]),
],
dependencies: [

],
targets: [
    .target(name: "SwiftCode", dependencies: ["Objective-CCode"]),
    .target(name: "Objective-CCode", dependencies: []),    
    ]
)

Module "Objective-CCode" with Objektive-C code: "Bridge.h"

#include <Foundation/Foundation.h>

@interface Bridge : NSObject

-(void) printHello;

@end

"Bridge.m"

#include "Bridge.h"

@implementation Bridge : NSObject

-(void)printHello {
    fprintf(stdout, "Hello from ExampleBridge\n");
}

@end

Module "SwiftCode" with Swift code

import Foundation
import Objective_CCode

class Examples {

    let e = Bridge()   // compiler error here

    func printH() {
        e.printHello()
    }
}
1 Answers

In the meantime I have searched for umbrella directory, which brought me to the solution.

This article https://medium.com/allatoneplace/challenges-building-a-swift-framework-d882867c97f9 explains the usage of the umbrella directory, which is needed to call the C* classes from swift.

For the above example the solution would be

Add an include directory to the Objective-C package with the following file "MixedExample.h"

#include "../Bridge.h"
Related