简体   繁体   English

从父母那里获取子类

[英]Get child class from parent

I have a big issue in Swift programming.我在 Swift 编程中有一个大问题。 I am trying to get the name of child class from the parent.我正在尝试从父级获取子类的名称。 This is a sample example, what i want to do:这是一个示例示例,我想做什么:

class Parent {
  class func sayHello() {
      let nameChildClass = //
      println("hi \(nameChildClass)")
  }
}

class Mother: Parent {

}

class Father: Parent {

}

Mother.sayHello()
Father.sayHello()

I know there is some other way do to that, but i really need to it like that.我知道还有其他方法可以做到这一点,但我真的需要那样做。

You can use a function like this:您可以使用这样的函数:

func getRawClassName(object: AnyClass) -> String {
    let name = NSStringFromClass(object)
    let components = name.componentsSeparatedByString(".")
    return components.last ?? "Unknown"
}

which takes an instance of a class and obtain the type name using NSStringFromClass .它接受一个类的实例并使用NSStringFromClass获取类型名称。

But the type name includes the namespace, so to get rid of that it's split into an array, using the dot as separator - the actual class name is the last item of the returned array.但是类型名称包括命名空间,因此为了摆脱它,它被拆分为一个数组,使用点作为分隔符 - 实际的类名是返回数组的最后一项。

You can use it as follows:您可以按如下方式使用它:

class Parent {
    class func sayHello() {
        println("hi \(getRawClassName(self))")
    }
}

and that will print the name of the actual inherited class这将打印实际继承类的名称

从 Swift 5.2

String(describing: Self.self)

You have to override the sayHello function in your child classes:您必须覆盖子类中的sayHello函数:

class Parent {
  class func sayHello() {
      println("base class")
  }
}

class Mother: Parent {
    override func sayHello() {
        println("mother")
    }
}

class Father: Parent {
    override func sayHello() {
        println("father")
    }
}

mother = Mother()
father = Father()

mother.sayHello()
father.sayHello()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM