Search code examples
swiftswift-package-manager

Importing modules with Swift package manager


I am trying to use Swift's package manager to import external modules in my project. My first module come from the Vapor project. I cannot seem to get it working. I start with

swift package init
swift package generate-xcodeproj

My Package.swift looks like this:

import PackageDescription

let package = Package(
    name: "OpenTools",
    products: [
        .library(
            name: "OpenTools",
            targets: ["OpenTools"]),
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/json.git", from: "2.0.0")
    ],
    targets: [
        .target(name: "OpenTools", dependencies: ["JSON"]),
    ]
)

I then run

swift package update
swift package generate-xcodeproj # to regenerate with dependencies

and then try to import the JSON package in my main file

import JSON

The modules are there as shown below but the import gets back with an No such module 'JSON' error.

enter image description here

Any thoughts?


Solution

  • Probably the problem lies within Xcode, as it does not know yet that JSON exists, because it was not built yet. This can easily be solved by just building your project (with cmd-B). With the generated xcodeproj, Xcode should know that it first needs to build JSON and then the rest, because JSON is marked as a dependency for your target.
    You can check this, by navigating in Xcode to your target (when you click on the project description file) and afterwards to "Build Phases". Under Target Dependencies you should find your JSON module.

    In addition you should find a JSON module under your targets, which compiles the sources you gathered from github.

    Your project should also build when executing swift build in your project root.