[英]Swift. How is it possible to get the name of an instance of a class within another class
Swift Jedi 可以幫助我嗎,我是 Swift 的新手。
There is class A and class B. Is it possible to get the name ( var name = Class A() ) of an instance of class A in the code of class B, which would then be added to the array.
您可以使用type(of: ...)
獲得 object 的 class 。 例子:
class A {
func test() {
print (type(of: self))
}
}
class B : A{
}
let a = A()
a.test()
let b = B()
b.test()
但是,此信息僅在運行時可用,而在編譯時不可用。 例如,您可以顯示 class 的名稱。 但是您不能動態創建該 class 的數組或變量。
如果你需要這個,你需要使用某種多態性來設計你的類。 如果所有類都有一個共同的基礎 class,您可以只定義一個基礎 class 的數組。 如果沒有,您可以考慮讓您設計的類共享一些通用協議:
protocol MySpecs {
func test()
}
class AA : MySpecs {
...
}
class BB : MySpecs {
...
}
var mylist = [ MySpecs ]()
mylist.append(AA())
mylist.append(BB())
for x in mylist {
x.test()
}
還有其他可能性。 但除非您提供更多詳細信息,否則很難在建議中更具體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.