Oscar Vasquez Oscar Vasquez - 2 months ago 10
Swift Question

Get Swift class name in "class func" method

I have a static method in Swift

class BaseAsyncTask: WebServiceClient {
class func execute(content : [String:AnyObject], cancelled:CustomBool)
{
// Print class name (BaseAsyncTask) here
}
}


And I want to know how to get the class name inside that method. I tried

self.dynamicType


but that gives error (I suppose because of the self inside a class function)

Answer

There are different methods to do that, if your method inherits from NSObject you can expose it to objective-c and do something like that.

@objc(BaseAsyncTask)

class BaseAsyncTask: WebServiceClient {
      class func execute(content : [String:AnyObject], cancelled:CustomBool)
      {
            println("Class \(NSStringFromClass(self))")
      }
}

For pure SWIFT introspection check here about MirrorType

I've found also this extension credits to ImpactZero

public extension NSObject{
    public class var nameOfClass: String{
        return NSStringFromClass(self).components(separatedBy: ".").last!
    }

    public var nameOfClass: String{
        return NSStringFromClass(type(of: self)).components(separatedBy: ".").last!
    }
}