21

In Swift, we can no longer use "self.class".

I want to print own class name for description method in subclass of NSObject.

How can I print it? Or I should make new method for getting class name?


I checked the following question, but I couldn't get the answer.

How do I print the type or class of a variable in Swift?

How do you find out the type of an object (in Swift)?

import UIKit

class PrintClassName: NSObject {
    override init() {
        super.init()
        println("\(self.dynamicType)")
        // Prints "(Metatype)"

        println("\(object_getClassName(self))");
        // Prints "0x7b680910 (Pointer)"

        println("\(self.className)")
        // Compile error!

        println(PrintClassName.self)
        // Prints "(Metatype)"
    }
}

 

2014.08.25 postscript

I checked the question.

Swift class introspection & generics

But println(PrintClassName.self) prints "(Metatype)"

And I want to get class name without writing the class name on source code.

Community
  • 1
  • 1
satomikko94
  • 273
  • 1
  • 2
  • 12
  • 1
    Though it doesn't answer your question, oddly enough the className property works in Swift when creating an OSX app. It is added as an extension to NSObject. For whatever reason, the extension isn't applied to iOS's version of NSObject. Perhaps it's just a bug. – Mallioch Aug 24 '14 at 23:06
  • 1
    Are you using Beta 6? *self.className* should give what you look for, since you inherit NSObject. Alternatively use **reflect(self).summary**. – vladof81 Aug 24 '14 at 23:50
  • 1
    @Mallioch self.className returns error "'PrintClassName' does not have a member named 'className'"... Okay, I understood it's a bug – satomikko94 Aug 25 '14 at 08:39
  • 1
    @vladof Yes, I'm using XCode6 beta6. But self.className returns error. But **reflect(self).summary** returns **ProjectName.ClassName** !! Thank you! – satomikko94 Aug 25 '14 at 08:41
  • You are probably looking for this http://stackoverflow.com/a/25345480/2866371 – ZaEeM ZaFaR Nov 12 '15 at 05:37

1 Answers1

39
import Foundation

class PrintClassName : NSObject {
    override init() {
        super.init()
        println(NSStringFromClass(self.dynamicType))
    }
}
Ivica M.
  • 4,763
  • 1
  • 23
  • 16