Get class name of object as string in Swift

Cover Image for Get class name of object as string in Swift
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

How to Get the Class Name of an Object as a String in Swift

Are you struggling to get the clean class name as a string in Swift? 🤔

If you have been using the object_getClassName method and ending up with a messy class name string like _TtC5AppName22CalendarViewController, don't worry! You are not alone. Many developers have stumbled upon this issue. In this blog post, we will address this common problem and provide you with easy solutions to get a cleaned up class name string in Swift. 💪

The Problem: Messy Class Name String

As you have already seen, using the object_getClassName method returns a cumbersome string that includes module information and other encrypted characters. This messy class name string isn't useful for many purposes, as you need a cleaned up version, like "CalendarViewController", to work with. So, how do we get the clean class name string? Let's dive into the solutions!

Solution 1: Using Swift's String Manipulation

Swift provides powerful string manipulation capabilities, allowing us to extract the class name substring from the messy string. Here's a straightforward solution:

func getCleanClassName(_ object: AnyObject) -> String? {
    let objectClassName = NSStringFromClass(type(of: object))
    let classComponents = objectClassName.components(separatedBy: ".")
    
    if let className = classComponents.last {
        return className
    }
    
    return nil
}

By utilizing the NSStringFromClass function and splitting the class name string by the dot separator, we can obtain an array of components. Taking the last component as the cleaner class name, we return it. With this solution, you will get the desired "CalendarViewController" as the cleaned up class name string.

Solution 2: Using Swift's Mirror

Another elegant approach to getting the clean class name string is by utilizing Swift's reflection capabilities. We can leverage the Mirror type to extract the class name without any messy module information. Let's take a look:

func getCleanClassName(_ object: AnyObject) -> String? {
    let objectMirror = Mirror(reflecting: object)
    
    if let className = objectMirror.subjectType.description().components(separatedBy: ".").last {
        return className
    }
    
    return nil
}

Here, we create a Mirror instance with the reflecting initializer, passing our object. Then, with the subjectType.description(), we obtain a cleaner class name string by splitting it and taking the last component. This solution provides you with the desired clean class name string as well.

Call-to-Action: Share Your Experience!

Getting the class name of an object as a string should no longer be a struggle for you. 🎉 Try out the solutions provided and pick the one that best suits your needs. If you have any other helpful methods to tackle this issue, share it with us in the comments section below. Let's help each other grow as developers! 👩‍💻👨‍💻

Remember, sharing is caring! Don't forget to share this blog post with your fellow Swift developers who might be facing the same problem. Spread the knowledge and let's make coding easier for everyone!

Happy coding! 😄✨


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello