我有一个函数,它需要一个类型为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")
}
但事实并非如此。什么是最顺利/最短的方式来实现我在找什么?
在这种情况下,为什么不使用基类中的名字? (因为动物和人都可以有名字) – giorashc
'attacker1.name as!人'这是错误的,请看[V.Khambirs'Ans](https://stackoverflow.com/a/44493238/5546312) – D4ttatraya
@giorashc他们不能。它是名称或物种。根据交给该职能的班级,它需要知道要求哪一个。 – Marmelador