Search code examples
objective-cswiftllvmswift-package-manager

How to use a swift module in an objective-c module with SwiftPM?


Here is an example of the root directory

├── Package.swift
└── Sources
    ├── Objc-cli
    │   └── main.m
    └── Swifty
        └── MyStruct.swift

Where the Swifty module is just a simple struct

// MyStruct.swift

public struct MyStruct {
    public var text = "Hello, World!"

    public init() {
    }
}

And in the Objc-cli I try to link the swift module like this.

// main.m

#import <Foundation/Foundation.h>
@import Swifty <---- Not found

int main() {
    NSLog(@"Hello from Objc");
    return 0;
}

Here is what the Package.swift looks like:

// Package.swift

import PackageDescription

let package = Package(
    name: "MyTest",
    targets: [
        Target(name: "Swifty", dependencies: []),
        Target(name: "Objc-cli", dependencies: ["Swifty"]),
    ]
)

Sadly the compiler doesn't recognise the Swifty module inside the objective-c module. Here is the output:

$ swift build
Compile Swift Module 'Swifty' (1 sources)
Compile Objc-cli main.m
/tmp/TestPackage/Sources/Objc-cli/main.m:10:9: fatal error: module 'Swifty' not found
@import Swifty
 ~~~~~~~^~~~~~
1 error generated.
<unknown>:0: error: build had 1 command failures

Have I missed something or is it simply impossible for now ?


Solution

  • Right now it's not possible to import Swift module in C module, it only works another way around, import C into Swift.

    You can find detailed information at SwiftPM - C language targets