swift - 将父类(super class)转换为其子类之一

标签 swift xcode casting

我有一个函数接受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")
    }

但事实并非如此。什么是实现我正在寻找的最顺利/最短的方法?

最佳答案

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

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

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

关于swift - 将父类(super class)转换为其子类之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44493140/

相关文章:

c++ - C++显式转换真的那么糟糕吗?

ios - swift 4 : UIImage from URL

ios - dyld : Library not loaded: @rpath/AnyFormatKit. 框架/AnyFormatKit

ios - View 设计未显示在 ViewController 中

ios - 快速将 UIPageControl 添加到 titleView

swift - 使用 Swift 5 在 Firestore 中获取字段的旧值

java - 需要在 Byte 和 Short 中进行转换

java - 如何转换 hashmap.values().toArray() ,其中这些 value() 也是 HashMap ?

javascript - 如何从 firebase 中的函数检索数据

ios - 触摸 UITextField 时设置 UIPickerView 的默认值