Get Class Name of Object as String in Swift

Getting class name in SWIFT equivalent to Objective C [self class]?

You can use print("Class = \(type(of: self))" in Swift.

Get class name of UIViewController in swift

To know your class name you can call something like this:

var className = NSStringFromClass(yourClass.classForCoder)

How to find a class instance name in other class in swift?

You can get variable name only in this way

class MyClass {
func printInstanceNameIn(user: User) {
let mirror = Mirror(reflecting: user)
for (label, value) in mirror.children {
if let value = value as? MyClass, value === self {
print(label!)
}
}
}
}

class User {
var firstObject: MyClass!
var secondObject: MyClass!
}

let u = User()
u.firstObject = MyClass()
u.secondObject = MyClass()
u.firstObject.printInstanceNameIn(user: u)

How to get a method’s defining class’s name?

I don't believe what you're specifically asking for is possible. There's no way I know of to evaluate something in your caller's context implicitly, except the provided #-literals.

That said, if you will change your syntax slightly, you can get the effect you want.

public class Logger {
public let caller: String

public init(for caller: Any) {
self.caller = "\(type(of: caller))"
}

public func info(_ message: String, file: String = #file, line: Int = #line, function: String = #function) {
print("Function \(function) of \(caller) in file \(file) was called.")
}
}

Now, in objects that use the logger, they just need to create their own with a consistent name like log. Make sure your Logger is stateless, so it's ok that they get created on demand.

class MyLoggingThing {
var log: Logger { Logger(for: self) }

func doSomething() {
log.info("Let's do this")
}
}

// Function doSomething() of MyLoggingThing in file MyPlayground.playground was called.

You can make this a little nicer with an extension, and handle static methods:

protocol Logging {}
extension Logging {
static var log: Logger { Logger(for: self) }
var log: Logger { Logger(for: self) }
}

class MyLoggingThing: Logging {
static func doSomethingStatic() {
log.info("Even static")
}
func doSomething() {
log.info("Let's do this")
}
}

Note that static methods will show the type as MyLoggingThing.Type. That's good or bad, depending on what you want. If you don't like the extra .Type, you can add an extra Logger.init like this:

public init(for staticCaller: Any.Type) {
self.caller = "\(staticCaller)"
}

That will cause types to be evaluated as themselves rather than as their metatypes.

If your logger is stateful or has a central configuration, or other situation where lots of loggers might be a problem, you should split apart the stateful "engine" part from this front-end. You can also make log a lazy var or otherwise initialize it in init when self is available.

In my personal Logging module, I also have a global "root" Logger called Log (with a leading capital). That makes it easier for functions that might not want to name themselves (such as top level functions or closures).

How can I print class name on Swift?

import Foundation

class PrintClassName : NSObject {
override init() {
super.init()
println(NSStringFromClass(self.dynamicType))
}
}

Get Swift class name in class func method

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

How to convert a string with the name of a class to the class type itself?

You can get your class back from string, but you need to use your project's module name while getting class name. If you don't use your module name then it will return nil because the class name you have referenced earlier is not fully qualified by the module name. You should change the class name string to represent the fully qualified name of your class:

let myClassString = String(MyModule.MyViewController.self)
print(myClassString)
let myClass = NSClassFromString("MyModule.\(myClassString)") as! MyViewController.Type
print(myClass)

Swift - get class name

Tuple is a compound type and compound types don't have names. You can get the types of its elements as you said. So your code in your question is the right way to get the type of variable. For example, code below will print the type of dictionary.

let someDictionary = ["Alex": 31, "Paul": 39]
print(type(of: someDictionary))

Output : Dictionary < String, Int >

You can have more detailed information about types from Swift Programming Language Reference.



Related Topics



Leave a reply



Submit