【发布时间】:2017-06-12 06:59:11
【问题描述】:
我有一个接受Being 类型实例的函数。 Being 有两个子类:Person 和 Animal。我希望该函数能够识别这两者中的哪一个被传递,并对每个子类的特定属性执行一些操作。
我认为这会起作用:
func fight(attacker1: Being, attacker2: Being) -> String {
if attacker1 is Person {
let name1 = attacker1.name as! Person //Error: Value of type Being has no member name
} else {
print("Its not a person")
}
但事实并非如此。实现我正在寻找的最顺畅/最短的方法是什么?
【问题讨论】:
-
在这种情况下为什么不在基类Being中使用name呢? (因为动物和人都可以有名字)
-
attacker1.name as! Person这个不对,看V.Khambirs' Ans -
@giorashc 他们不能。它要么是名称,要么是物种。并且根据传递给函数的类,它需要知道要请求哪一个。