如何从具有同名嵌套类型的 class 中引用全局类型?

How to refer to a global type from within a class that has a nested type with the same name?

我有一个在全局范围声明的 class 和另一个嵌套在某些 class 中的同名 class。

class Address {
    var someProperty: String?
}

class ThirdPartyAPI {
    class Address {
        var someOtherProperty: String?
        init(fromAddress address: Address) {
            self.someOtherProperty = address.someProperty
        }
    }
}

问题是:如何从其初始化程序中引用全局 class 而不是内部的?在给出的示例中,我遇到了一个错误 Value of type 'ThirdPartyAPI.Address' has no member 'someProperty',这意味着编译器引用了内部 Address 而不是全局的。

使用typealias

class Address {
    var someProperty: String?
}

typealias GlobalAddress = Address

class ThirdPartyAPI {
    class Address {
        var someOtherProperty: String?
        init(fromAddress address: GlobalAddress) {
            self.someOtherProperty = address.someProperty
        }
    }
}

您可以通过在模块名称前加上唯一的方式来引用类型。 所以如果

class Address {
    var someProperty: String?
}

在 "MySuperApp" 中定义,那么您可以将其称为 MySuperApp.Address:

class ThirdPartyAPI {

    class Address {
        var someOtherProperty: String?
        init(fromAddress address: MySuperApp.Address) {
            self.someOtherProperty = address.someProperty
        }
    }
}

(但如果你有选择,那么尽量避免歧义 你的代码更容易理解。)