如何将Objective-C通过字符串获取类并传参的逻辑转为Swift实现?
Convert Objective-C Dynamic Class Initialization to Swift
Let's walk through converting your Objective-C logic to complete Swift code, with safety checks to avoid runtime crashes.
First, let's recap your original Objective-C logic: you're fetching a class name from the backend, resolving the corresponding UIViewController subclass, and initializing it with an appRenderer object.
Here's the complete, safe Swift implementation:
func getUIViewController() -> UIViewController? { let templateID = "templateId" // Replace with your actual backend-provided value // Get your app's module name (matches your target name, required for Swift class lookup) guard let moduleName = Bundle.main.infoDictionary?["CFBundleName"] as? String else { print("Failed to retrieve module name") return nil } // Construct the full class name (Swift classes are scoped to their module) let fullClassName = "\(moduleName).\(templateID)" // Resolve the class and cast it to a UIViewController subclass type guard let viewControllerClass = NSClassFromString(fullClassName) as? UIViewController.Type else { print("Could not find or cast class: \(fullClassName)") return nil } // Initialize the view controller with your custom initializer guard let vc = viewControllerClass.init(appRender: appRenderer) as? UIViewController else { print("Failed to initialize view controller with appRenderer") return nil } return vc }
Key Details to Note:
- Module Name Requirement: Unlike Objective-C, Swift classes are namespaced under your app's module (usually your target name).
NSClassFromStringneeds the full qualified name (module + class name) to locate the class correctly. - Safety Checks: We use
guardstatements at each step to gracefully handle failures (e.g., missing module name, invalid class name, initialization failure) instead of letting the app crash. - Type Casting: We cast the resolved
AnyClasstoUIViewController.Typeto ensure we can call the custom initializer safely.
Make sure your UIViewController subclass explicitly implements the init(appRender:) initializer, and that it's accessible (e.g., marked internal or public depending on your module setup).
内容的提问来源于stack exchange,提问作者Sivakrishna Perla
相关产品推荐
相关产品推荐

