Get child class from parent

I have a big problem in Swift programming. I am trying to get the name of a child class from a parent. This is the example 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 are other ways, but I really need to do this.

+3


source to share


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 a class instance and gets the type name with NSStringFromClass

.

But the type name includes a namespace, so to get rid of splitting it into an array using a dot as a separator - the actual class name is the last element of the returned array.



You can use it like this:

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

      

and this will print the name of the actual inherited class

+4


source


You must override the function sayHello

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

      

0


source







All Articles