繁体   English   中英

Swift。 如何在另一个 class 中获取 class 实例的名称

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM