将超类强制转换为其子类之一

Mar*_*dor 1 xcode casting swift

我有一个函数,它接受一个类型的实例Being.有两个子类Being:PersonAnimal.我希望函数能够识别两者中的哪一个被传递,并使用特定于每个子类的属性执行某些操作.

我认为这会奏效:

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")
    }
Run Code Online (Sandbox Code Playgroud)

但事实并非如此.实现我想要的最顺畅/最短的方式是什么?

Vla*_*bir 6

您应该创建所需类型的新变量,并将参数放入此变量中.

func fight(attacker1: Being, attacker2: Being) -> String {
    if let att1 = attacker1 as? Person {
        let name1 = att1.name
    } else {
        print("Its not a person")
    }
Run Code Online (Sandbox Code Playgroud)

这样,如果attacker1是Person,则只需将此值保存为att1常量,稍后您可以将此常量用作Person类型的实例.