繁体   English   中英

当另一个模块在 Swift 中具有自己的名称时,引用另一个模块中的类型与当前模块中的类型同名

[英]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 ,它导出两种类型: ModuleATest 我有一个模块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'

但是当publicModuleA中的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM