iOS Objective C project: NSClassFromString method for Swift classes

If you use Swift classes in the Objective C project, you maybe 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 name of project is different than name of target you need to use the following format:

#appName_#targetName.#className

As 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;
}
}
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.