Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 247
Oscar Vasquez Avatar asked Aug 04 '15 02:08

Oscar Vasquez


2 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!
}
like image 147
Andrea Avatar answered Sep 30 '22 18:09

Andrea


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"
like image 23
Antonio Avatar answered Sep 30 '22 17:09

Antonio