[英]How to reference a type in a module that has a type with the same name as the module it is in?
[英]Referring to a type in another module with the same name as a type in the current module when the other module has a type with its own name in Swift
我正在使用 swift package 管理器。 我有一个模块ModuleA
,它导出两种类型: ModuleA
和Test
。 我有一个模块ModuleB
,它定义了一个类型: Test
。 在ModuleB
中,如何从ModuleA
引用类型Test
? 理想情况下,我希望#module(ModuleA)
类的语法直接引用模块ModuleA
。
可重现的例子:
Package.swift
:
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "ShadowingTest",
products: [
.library(
name: "ModuleA",
targets: ["ModuleA"]),
.library(
name: "ModuleB",
targets: ["ModuleB"]),
],
dependencies: [
],
targets: [
.target(
name: "ModuleA",
dependencies: []),
.target(
name: "ModuleB",
dependencies: ["ModuleA"]),
]
)
Sources/ModuleA/ModuleA.swift
:
public enum ModuleA {}
public struct Test {
public static let module: String = "ModuleA"
}
Sources/ModuleB/ModuleB.swift
:
import ModuleA
struct Test {
static let module: String = "ModuleB"
}
func test() {
print(ModuleA.Test.module)
}
运行swift build
错误
Sources/ModuleB/ModuleB.swift:8:19: error: type 'ModuleA' has no member 'Test'
但是当public
从ModuleA
中的ModuleA
枚举中删除时成功。
问题是 ModuleA 模块中的ModuleA
枚举没有Test
。
当您在ModuleA enum
中删除public
时, ModuleB
无法识别存在ModuleA enum
,因为它的访问修饰符默认为internal
,因此ModuleB
识别ModuleA
中的Test
结构,而不是尝试在ModuleA enum
中查找Test
奖励:SO中有一个关于访问修饰符的答案,我认为您会发现它很有用。
编辑:
如果你需要使用ModuleA.Test
即使有一个名为ModuleA
的枚举,那么你可以使用import (class|struct|func|protocol|enum) <needed_component>
所以在你的情况下你应该像这样导入:
import struct ModuleA.Test
如果您想使用具有其他名称的结构以避免命名冲突,那么您可以设置 typealias ->
import struct ModuleA.Test
typealias TestA = ModuleA.Test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.