我有类Fruit作为基类。我创建了另外两个继承自Fruit的类:Apple和Orange。
我需要在数组中添加苹果和橘子。我想要那个数组的Fruit类。有可能吗?
如果是这样,我如何从该数组中读取项目并定义它的类。
样品:
var ar: [Fruit] = [Apple, Apple, Orange]
for i in ar {
if i is Apple {
...
} else if i is Orange {
...
}
}
答案 0 :(得分:1)
鉴于此
class Fruit { }
class Apple: Fruit { }
class Orange: Fruit { }
如果Fruit(s)
var fruits: [Fruit] = []
您可以添加Apple
fruits.append(Apple())
或橙色
fruits.append(Orange())
for fruit in fruits {
switch fruit {
case let apple as Apple: print(apple)
case let orange as Orange: print(orange)
default: print("Another fruit")
}
}