Yes, in Swift 5.9, you can absolutely print out an object's class hierarchy by leveraging Swift's reflection capabilities, specifically type(of:) and the superclass() method available on AnyClass.
Here's a method to do it, along with explanations and examples:
import Foundation // Needed for NSObject, UIView, etc., and NSStringFromClass
/// Prints the class hierarchy of a given object.
///
/// - Parameter object: The object whose class hierarchy you want to inspect.
func printClassHierarchy(of object: Any) {
var currentClass: AnyClass? = type(of: object)
var hierarchy: [String] = []
print("--- Class Hierarchy for \(String(describing: object)) ---")
while let cls = currentClass {
// NSStringFromClass gives a cleaner class name without module prefix
// (e.g., "MyClass" instead of "MyApp.MyClass").
// For built-in types (like Int, String), String(describing: cls) is fine.
let className = NSStringFromClass(cls)
hierarchy.append(className)
// Get the superclass of the current class
currentClass = cls.superclass()
}
// Print the hierarchy from the most specific class down to the root
for (index, className) in hierarchy.enumerated().reversed() {
let indent = String(repeating: " ", count: index)
print("\(indent)↳ \(className)")
}
print("------------------------------------------\n")
}
// MARK: - Example Classes
// Pure Swift classes (implicitly inherit from _TtCs12_SwiftObject, Swift's internal root for Any/AnyObject)
class Vehicle {
let wheels: Int
init(wheels: Int) { self.wheels = wheels }
}
class Car: Vehicle {
let make: String
init(make: String, wheels: Int = 4) {
self.make = make
super.init(wheels: wheels)
}
}
class ElectricCar: Car {
let batteryCapacity: Int
init(make: String, batteryCapacity: Int) {
self.batteryCapacity = batteryCapacity
super.init(make: make)
}
}
// Classes inheriting from Objective-C Foundation types (NSObject, UIView, etc.)
// These will clearly show the NSObject chain.
class MyCustomView: UIView {
// Add some custom properties or methods if needed
}
class MySpecialButton: UIButton {
// Custom button logic
}
// MARK: - Usage Examples
let myElectricCar = ElectricCar(make: "Tesla", batteryCapacity: 100)
printClassHierarchy(of: myElectricCar)
let aVehicle = Vehicle(wheels: 2) // Could be a bicycle!
printClassHierarchy(of: aVehicle)
let customView = MyCustomView()
printClassHierarchy(of: customView)
let specialButton = MySpecialButton(type: .system)
printClassHierarchy(of: specialButton)
// Even works for basic types, though their "hierarchy" is just themselves
printClassHierarchy(of: 42)
printClassHierarchy(of: "Hello Swift")
printClassHierarchy(of: UIView()) // An instance of a built-in class
Explanation:
import Foundation: This is necessary because NSObject, UIView, UIButton, and the NSStringFromClass function are part of the Foundation framework.
type(of: object): This function returns the dynamic type of the object instance at runtime. For a Car instance, it returns the Car.Type (which is an AnyClass).
var currentClass: AnyClass?: We use an optional AnyClass to iterate through the hierarchy. AnyClass is a type alias for AnyObject.Type, which is the metatype for any class.
while let cls = currentClass: The loop continues as long as currentClass holds a valid class type.
NSStringFromClass(cls): This Objective-C bridge function is useful for getting the class's name as a String without the module prefix (e.g., MyApp.MyClass becomes MyClass). If you prefer the full qualified name, you could use String(describing: cls).
hierarchy.append(className): We collect the class names into an array.
cls.superclass(): This is the core method. It's called on the AnyClass instance (cls) and returns its direct superclass as an optional AnyClass?. If there's no superclass (e.g., for NSObject or Swift's internal root class), it returns nil, terminating the loop.
- Printing in Reverse: We
reversed() the hierarchy array and then enumerated() it to get both the index and the class name. This allows us to print from the top-level superclass down to the specific instance's class, with increasing indentation for better visualization.
_TtCs12_SwiftObject: For pure Swift classes that don't inherit from NSObject, their ultimate root superclass will be _TtCs12_SwiftObject. This is an internal Swift runtime class representing the base of all Swift objects that don't bridge to NSObject.
NSObject: For classes that inherit from NSObject (directly or indirectly, like UIView -> UIResponder -> NSObject), NSObject will be their ultimate root.
This method provides a clear and readable output of an object's complete inheritance chain.