Swift
programming
class name
object-oriented
string conversion

Get class name of object as string in Swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Swift, retrieving the class name of an object as a string can be an essential technique for debugging, logging, or when you need some level of reflection. Swift provides several ways to accomplish this, relying heavily on metaprogramming and introspection capabilities. This article breaks down the methods, their technical workings, and when to use each approach.

Methods of Retrieving Class Name as a String

1. Using String(describing:)

The String(describing:) initializer can be used to convert an object's type into a string representation. It's straightforward and commonly used for obtaining type information for debugging purposes.

Example

swift
1class ExampleClass {
2}
3
4let instance = ExampleClass()
5let className = String(describing: type(of: instance))
6print(className)  // Outputs: "ExampleClass"

Explanation

  • type(of:): This function returns the runtime type of a value, perfect for retrieving the type of a class instance.
  • String(describing:): Converts the result of type(of:) into a string highlighting its human-readable class name.

2. Using NSStringFromClass

The Foundation framework provides the NSStringFromClass function, which gives a fully qualified class name. This is particularly useful when working with Objective-C interoperability or when a namespace is involved.

Example

swift
1import Foundation
2
3@objc class CustomObject: NSObject {
4}
5
6let instance = CustomObject()
7let className = NSStringFromClass(type(of: instance))
8print(className)  // Outputs: "ModuleName.CustomObject"

Explanation

  • By using NSStringFromClass, you get a fully qualified name, which includes the module name, acting as a namespace.
  • This can be beneficial when you have classes with the same name in different modules and need to distinguish them.

3. Using Mirror

The Mirror class is part of Swift’s reflection API, enabling introspection capabilities to inspect or retrieve metadata about an object.

Example

swift
1class AnotherExample {
2}
3
4let instance = AnotherExample()
5let mirror = Mirror(reflecting: instance)
6let className = String(describing: mirror.subjectType)
7print(className)  // Outputs: "AnotherExample"

Explanation

  • Mirror: Represents a dynamic view into an instance and its type.
  • mirror.subjectType: Provides access to the type being mirrored, which can be transformed into a string representation.

Considerations

  • Namespaces: If you require the module or namespace information, prefer NSStringFromClass.
  • Readability: For concise and readable output, String(describing:) is usually sufficient and easier to work with.
  • Performance: While Mirror provides a more detailed reflection and might be beneficial for more advanced use cases, it’s typically costlier in terms of performance.

Summary Table

MethodDescriptionUsage
String(describing:)Converts a type to a human-readable string.Use when a simple, readable class name is sufficient.
NSStringFromClassRetrieves a fully qualified class name.Use when dealing with namespaces or modules in complex projects.
MirrorProvides a reflective view for introspection.Use for advanced reflection capabilities and when inspecting object.

Understanding Type Retrieval Mechanisms

Swift’s emphasis on type safety and performance makes direct reflection and type inspection less straightforward compared to dynamic languages. However, these methods preserve efficiency while still providing the necessary inspection tools:

  • Type Safety: Each method respects Swift’s type constraints, ensuring any retrieved type name is accurate, leveraging compile-time and runtime checks.
  • Introspection vs. Reflection: Generally, introspection is lighter, as seen with String(describing:), aimed at obtaining basic information. Full reflection, as with Mirror, provides a richer dataset but may be overkill for simple tasks.
  • Framework Integration: The Objective-C bridge and Foundation’s availability makes NSStringFromClass a viable option in mixed-language projects.

Being able to accurately and efficiently determine the class name of an object in Swift aids in debugging, logging, middleware programming, and more, facilitating a smoother development and maintenance workflow. By choosing the right method for your use case, you can maximize both performance and clarity in your Swift applications.


Course illustration
Course illustration

All Rights Reserved.