我有一个各种类型的对象数组和一个类型数组。对于每个对象,我想遍历类型数组并查看该对象是否是该类型。像这样:
class Parent {}
class ChildA: Parent {}
class ChildB: Parent {}
class GrandChildA: ChildA {}
var objects: [Any] = ["foo", ChildA(), ChildA(), ChildB(), GrandChildA()]
var classes = [Parent, ChildA, ChildB] // This line doesn't compile!!
for obj in objects {
for cls in classes {
if obj is cls {
NSLog("obj matches type!")
}
}
}
这行不通,因为您不能将类存储在数组中。据我了解,您可以存储类类型,例如 ChildA.self
:
ChildA().dynamicType == ChildA.self // true
但这不处理子类:
ChildA().dynamicType == Parent.self // false
显然 is
运算符解决了子类的情况:
ChildA() is Parent // true
但是如果我想使用is
,我不知道如何将类类型存储在数组中。
我能否使用 Swift 和一些反射巫术以某种方式完成我想要的事情?
如果标题有误导性,我很抱歉——我对这个问题的理解还不足以形成一个正确的问题。
通过为每个类添加标题,您可以打开它们。另外,您是否考虑过使用协议(protocol)而不是父类(super class)?
也许是这样的:
protocol Parentable {
var title : String { get set }
}
class ChildA : Parentable{
var title: String
init() {
self.title = "ChildA"
}
init(title: String){
self.title = title
}
}
class ChildB: Parentable {
var title: String
init(){
self.title = "ChildB"
}
}
class GrandChildA: ChildA {
override init() {
super.init(title: "GrandChild")
}
}
var objects: [Parentable] = [ChildA(), ChildA(), ChildB(), GrandChildA()]
for obj in objects {
switch obj.title {
case "ChildA":
print("Object is of type \(obj.title)")
case "ChildB":
print("Object is of type \(obj.title)")
case "GrandChild":
print("Object is of type \(obj.title)")
default :
print("Object is of type \(obj.title)")
}
}
如果您需要通过引用传递的对象,您也可以使用这样的父类(super class)来实现:
class Parent {
var title: String
init() {
self.title = "Parent"
}
init(title: String) {
self.title = title
}
}
class ChildA: Parent {
override init() {
super.init(title: "ChildA")
}
override init(title: String) {
super.init(title: title)
}
}
class ChildB: Parent {
override init() {
super.init(title: "ChildB")
}
}
class GrandChildA: ChildA {
override init() {
super.init(title: "GrandChild")
}
}
var objects: [Parent] = [ChildA(), ChildA(), ChildB(), GrandChildA()]
for obj in objects {
switch obj.title {
case "ChildA":
print("Object is of type \(obj.title)")
case "ChildB":
print("Object is of type \(obj.title)")
case "GrandChild":
print("Object is of type \(obj.title)")
default :
print("Object is of type \(obj.title)")
}
}