Home » Swift » Get Swift class name in “class func” method

Get Swift class name in “class func” method

Posted by: admin November 30, 2017 Leave a comment

Questions:

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)

Answers:

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!
    }
}

[Xcode 8]
Alex suggested me that in the Xcode 8 version this code shows a warning. To avoid that we should prefix the method like that:

@nonobjc class var className: String{ 
   return NSStringFromClass(self).components(separatedBy: ".").last!
}

Questions:
Answers:

You can use string interpolation to print self:

let className = "\(self)"

Sample code:

class BaseAsyncTask: WebServiceClient {
    class func execute(content : [String:AnyObject], cancelled: CustomBool)
    {
        let className = "\(self)"
        print(className)
    }
}

class AnotherAsyncTask : BaseAsyncTask {
}

BaseAsyncTask.execute([:], cancelled: true) // prints "BaseAsyncTask"
AnotherAsyncTask.execute([:], cancelled: true) // prints "AnotherAsyncTask"

Questions:
Answers:

Another way to do this, when you don’t have an instance of the class is this.

print(String(BaseAsyncTask))

Inspired here.

Get class name of object as string in Swift