我有一个班级:
class MyClass<T> {
func whoAreYou() {
print("I am \(T.self)")
}
}
我创建了两个实例:
let a = MyClass<Int>()
let b = MyClass<Double>()
我想把它们放在一个数组中并迭代它们,但我没有做到。我试过了:
// not working
let objects: [MyClass<Any>] = [a as! MyClass<Any>, b as! MyClass<Any>]
for object in objects {
object.whoAreYou()
}
我也尝试过:
// not working
for object in [a, b] {
object.whoAreYou()
}
任何人都知道怎么做?
答案 0 :(得分:5)
如果您创建协议,这将起作用,如下所示:
protocol Identifiable {
func whoAreYou()
}
然后,使您的班级符合您创建的协议:
class MyClass<T>: Identifiable {
func whoAreYou() {
print("I am \(T.self)")
}
}
创建班级的实例:
let a = MyClass<Int>()
let b = MyClass<Double>()
稍后在您的代码中:
for object in [a, b] as [Identifiable] {
object.whoAreYou()
}
或者这个:
let objects: [Identifiable] = [a, b]
for object in objects {
object.whoAreYou()
}