Access Struct in depended Swift package with same name

I have a Swift package (PackageA) which has an other package (PackageB) as dependency added. Both packages have a Struct which is called Station. In the most cases the complier decided correctly which type is required. Now I want to create a function in PackageA which explicitly requires Station from PackageB.

func toSomething(with station: PackageB.Station) { }

But I always this error:

'Station' is not a member type of class 'PackageB.PackageB'

Is there anything als I need to do?

Here are some more details:

Package.swift from PackageB:

// swift-tools-version: 5.9

import PackageDescription

let package = Package(
    name: "PackageB",
    platforms: [
        .iOS(.v17),
        .watchOS(.v10)
    ],
    products: [
        .library(
            name: "PackageB",
            targets: ["PackageB"]
        )
    ],
    targets: [
        .target(
            name: "PackageB"
        )
    ]
)

Package.swift from PackageA:

// swift-tools-version: 5.9

import PackageDescription

let package = Package(
    name: "PackageA",
    platforms: [
        .iOS(.v17),
        .watchOS(.v10)
    ],
    products: [
        .library(
            name: "PackageA",
            targets: ["PackageA"])
    ],
    dependencies: [
      .package(name: "PackageB", path: "../PackageB")
    ],
    targets: [
        .target(
            name: "PackageA",
            dependencies: [
              .product(name: "PackageB", package: "PackageB"),
            ]
        )
    ]
)

The Station Struct looks in both packages like this:

#import Foundation

public struct Station { }

Do you have a class named PackageB in PackageB? If so, the error is because compiler can't tell if you refer to the class or the module. There were discussion about the issue in the forum. I don't have the link, but if I remember it correctly it's an old issue and there isn't a solution.

2 Likes

You are right, that was my problem.

Thanks for your help.

Could a solution be to create a file that only imports PackageB and defines a type alias:

// FileA.swift
import PackageA
typealias StationA = Station

// FileB.swift
import PackageB
typealias StationB = Station

// FileC.swift
func toSomething(with station: StationB) { 
  // ...
}

The OP specifically wants to write the function in PackageA; I can't think of a solution which doesn't require modifying PackageB.

1 Like

Right. I didn't catch that.