简体   繁体   中英

Get child class from parent

I have a big issue in Swift programming. 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 .

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:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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