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
From Swift 5.2
String(describing: Self.self)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With