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