[英]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.