You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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). NSClassFromString needs the full qualified name (module + class name) to locate the class correctly.
  • Safety Checks: We use guard statements 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 AnyClass to UIViewController.Type to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:22:28