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

对着背影说爱祢 提交于 2019-12-23 17:17:59

问题


I have a class declared at the global scope and another class with the same name that is nested within some class.

class Address {
    var someProperty: String?
}

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

The question is: how can I refer to a global class instead of the inner one from its initialiser? In the example given I've got an error Value of type 'ThirdPartyAPI.Address' has no member 'someProperty', which means that compiler refers to the inner Address instead of a global one.


回答1:


Use typealias

class Address {
    var someProperty: String?
}

typealias GlobalAddress = Address

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



回答2:


You can refer to types uniquely by prepending the module name. So if

class Address {
    var someProperty: String?
}

is defined in "MySuperApp" then you can refer to it as MySuperApp.Address:

class ThirdPartyAPI {

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

(But if you have a choice then try to avoid the ambiguity to make your code easier to understand.)



来源:https://stackoverflow.com/questions/34380112/how-to-refer-to-a-global-type-from-within-a-class-that-has-a-nested-type-with-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!