Search code examples
swift-package-manager

Swift Package Manager cannot find a neighboring folder/class in Sources


Goal: To access neighboring folder/classes within the source folder.

Scenario: I have two classes:

  1. RicPackage (default) and
  2. Apple

The 'RicPackage' was auto-generated upon the creation of the Swift Package 'RicPackage'.
I want to expand and try to access other folders w/classes autonomously.

Here's the manifest that I'm working on:

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

import PackageDescription

let package = Package(
    name: "RicPackage",
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "RicPackage",
            targets: ["RicPackage"]),
        .library(
            name: "Apple",
            targets: ["Apple"]),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "RicPackage",
            dependencies: []),
        .target(
            name: "Apple",
            dependencies: []),
        .testTarget(
            name: "RicPackageTests",
            dependencies: ["RicPackage"]),
    ]
)

I want to be able to access 'Apple' and other such folders independently from the host program.

Here's the Apple source code:

import Foundation

class Apple {
    public private(set) var text = "Hello from Apple!"

    public init() {
    }
    
    public func eat() -> String {
        print("Inside Eat Apple")
        return "Hello from Eat Apple."
    }
}

Here's the test. Once I get this to work, I'll try to access it from the host application.

enter image description here

I believe that classes & functions must be 'pubic' to be seen.

Questions:

  1. What am I doing wrong with the package manifest file?
  2. Must a target class file have the same name as its folder container? ... for example: 'Apple/Apple.swift'.

Solution

  • So in RicPackageTest, you can't find Apple. Is there an import missing? Not necessarily, you won't find it either.

    It's because in the way that RicPackageTest is constructed it has no knowledge of the Apple package.

    You wrote:

    .testTarget(
        name: "RicPackageTests",
        dependencies: ["RicPackage"]),
    

    That's what's missing, you aren't saying that RicPackageTests should "depend" (ie "knows of") Apple package.

    So you should do:

    .testTarget(
        name: "RicPackageTests",
        dependencies: ["RicPackage", "Apple"]),