2015-12-20 65 views
2

我有一個在全局範圍聲明的類和另一個具有相同名稱的嵌套在某個類中的類。如何從具有相同名稱的嵌套類型的類中引用全局類型?

class Address { 
    var someProperty: String? 
} 

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

現在的問題是:我如何從它的初始化程序引用全局類而不是內部類?在給出的示例中,我得到了一個錯誤Value of type 'ThirdPartyAPI.Address' has no member 'someProperty',這意味着編譯器引用內部的Address而不是全局的。

回答

6

使用typealias

class Address { 
    var someProperty: String? 
} 

typealias GlobalAddress = Address 

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

哇!這很容易。萬分感謝! –

2

你可以參考各類唯一在前面加上模塊的名字。 所以如果

class Address { 
    var someProperty: String? 
} 

在「MySuperApp」的定義,那麼你可以稱其爲 MySuperApp.Address

class ThirdPartyAPI { 

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

(但如果你有一個選擇,然後儘量避免歧義,使 您代碼更容易理解。)

相關問題