protocol TestProtocol {
init()
}
class Person: NSObject, TestProtocol {
required override init() {
super.init()
}
}
class Man: Person {
}
class Women: Person {
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let classes: [TestProtocol.Type] = [Person.self, Man.self, Women.self]
classes.forEach { (type) in
let obj = type.init()
print(obj)
}
}
}
我尝试在Xcode10.2中执行这些代码,Swift版本配置为Swift 5,我希望得到Person,Man和Women的实例,但是控制台结果是:
<TestSwift5.Person: 0x6000006eb3e0>
<TestSwift5.Person: 0x6000006eb3e0>
<TestSwift5.Person: 0x6000006eb3e0>
这让我感到困惑,任何人都可以解释它。
期待你的回答,谢谢。
从NSObject到本机Swift子类的子类中存在一些关键差异。
Swift native base class or NSObject
我不是确切原因的专家,但它与Objective-C运行时和NSObject获得的额外元数据有关。
在您的示例中,如果您不从NSObject创建子类,您将看到控制台输出与您期望的一致。
在处理表视图和集合视图单元格时,我自己遇到了这个问题。我尽可能避免使用NSObject子类化,但是当它不可避免时,我还从description
自定义CustomStringConvertible属性以获得我需要的东西。
您可以使用像Reflection这样的技术来充分利用它。
protocol TestProtocol {
init()
}
class Person: TestProtocol {
required init() {
}
}
class Man: Person {
required init() {
super.init()
}
}
class Women: Person {
}
当您在Xcode或游乐场中运行它们时,您将获得以下内容:
__lldb_expr_16.Person
__lldb_expr_16.Man
__lldb_expr_16.Women