Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child class from parent

Tags:

ios

swift

ios8

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.

like image 555
user2724028 Avatar asked Oct 23 '14 10:10

user2724028


2 Answers

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

like image 190
Antonio Avatar answered Oct 11 '22 21:10

Antonio


From Swift 5.2

String(describing: Self.self)
like image 24
Artyom Avatar answered Oct 11 '22 21:10

Artyom