2017-07-25 69 views
0

我被卡住了。 我儘量讓正確的代碼的設計師,但我解決不了下面的情況: 我有一些基類繼承自它的類,如:如何通過基類獲得子類中的某些參數

class BaseClass { 
    var name: String 
    init(name: String) { 
     self.name = name 
    } 
} 

class ChildClass: BaseClass { 
    var otherName: String 
    init(otherName: String) { 
     self.otherName = otherName 
    } 
} 

而下面的功能:

func someFunc() -> BaseClass { 
    let a = ChildClass.init(otherName: "NAME") 
    return a 
} 

哪有我得到參數「otherName」? 可用的參數只有一個 - 「名」,但我想「中文別名」:

let b = someFunc() 
b.PARAMETERS 

回答

0

您可以使用:

(b as! ChildClass).otherName 

你的函數返回的對象作爲BaseClass對象,所以你不能訪問任何ChildClass方法。爲了訪問ChildClass方法,您需要使用as!將對象投射到ChildClass,因爲我們知道它是一個ChildClass對象。之後,您將可以訪問ChildClass的所有參數。

+0

謝謝!我忘了它 – Movash

+0

不客氣! :) –

相關問題