我有一个函数,它接受一个 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")
}
但这样做不行。实现我想要的最顺畅/最短的方法是什么?
attacker1.name as! Person
这是错误的,看看 V.Khambirs' Ans。 - D4ttatraya