iOS Objective C project: NSClassFromString method for Swift classes

If you use Swift classes in the Objective C project, you may be faced with the problem, that NSClassFromString method always returns nil. You need to call NSClassFromString from Swift code first of all, and don’t forget about format:

#appName.#className

But if you have many targets in your project or the name of the project is different than the name of the target you need to use the following format:

#appName_#targetName.#className

As a solution, I provide the following extension for NSObject:

extension NSObject {
class func swiftClassFromString(className: String) -> AnyClass! {
if var appName: String? = NSBundle.mainBundle().objectForInfoDictionaryKey(“CFBundleName”) as! String? {
let fAppName = appName!.stringByReplacingOccurrencesOfString(“ “, withString: “_”, options: NSStringCompareOptions.LiteralSearch, range: nil)
return NSClassFromString(“\(fAppName).\(className)”)
}
return nil;
}
}

--

--

Software Engineer at @MySwimPro |  swift/objc/c++ | 🇺🇦 | family 👨‍👩‍👧 | swimmer 🏊‍♂️ | optimist ⚡️ | superhero for my 👧

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Maksym Bilan

Software Engineer at @MySwimPro |  swift/objc/c++ | 🇺🇦 | family 👨‍👩‍👧 | swimmer 🏊‍♂️ | optimist ⚡️ | superhero for my 👧