Nutritioustim
Nutritioustim

Reputation: 2738

Loading Swift library: "error: no such module"

Newbie Swift question here. If I make 2 Swift projects - an executable and a library , I'm having problems calling the library from the executable.

A) So if we create the projects like so:

~ $ mkdir Foo Bar
~ $ cd Foo/
Foo $ swift package init --type executable
Foo $ cd ../Bar/
Bar $ swift package init --type library

Bar $ git init .
Bar $ git add .
Bar $ git commit -m "Initial commit"
Bar $ git tag 1.0.0
Bar $ swift build

B) From here, if I try to include "Bar" from "Foo", I get error: no such module 'Bar'.

This looks like a Swift PATH issue. So I'm certainly missing something really basic. Can someone point out what I'm missing?

File: Package.swift

  // swift-tools-version:4.0
  // The swift-tools-version declares the minimum version of Swift required to build this package.

  import PackageDescription

  let package = Package(
      name: "Foo",
      dependencies: [
          .package(url: "../Bar", from: "1.0.0"),
      ],
      targets: [
          .target(
              name: "Foo",
              dependencies: []),
      ]
  )

File: Sources/Foo/main.swift

  import Bar
  print("Hello, world!")

swift build

Bar $ cd ../Foo
Foo $ swift build

Compile Swift Module 'Foo' (1 sources)
Foo/Sources/Foo/main.swift:1:8: error: no such module 'Bar'
import Bar
       ^
error: terminated(1): /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f Foo/.build/debug.yaml main

Version

$ swift --version
Apple Swift version 4.0.3 
Target: x86_64-apple-macosx

Upvotes: 3

Views: 544

Answers (1)

Nutritioustim
Nutritioustim

Reputation: 2738

So it seems like you need to include "dependencies" twice. Once in the "dependencies" section, once in the "targets" section. Thanks @user9335240.

import PackageDescription

let package = Package(
    name: "Foo",
    dependencies: [
      .package(url: "../Bar", from: "1.0.0"),
    ],
    targets: [
        .target(
            name: "Foo",
            dependencies: ["Bar"]),
    ]
)

Upvotes: 4

Related Questions