简体   繁体   中英

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)

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

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"

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

Swift 4

print(String(describing:BaseAsyncTask.self))

Swift 2

print(String(BaseAsyncTask))

Inspired here.

Get class name of object as string in Swift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM