Playground App崩溃:无法将LLAppDelegateProxy转为SwiftUI.AppDelegate求助
问题原因
Playground的运行机制和常规iOS应用不同,它会自动生成LLAppDelegateProxy代理类包装你自定义的AppDelegate。你代码中显式指定delegate的类型为AppDelegate,导致系统尝试将生成的代理类实例强制转换为自定义类,触发类型转换错误,引发Thread 1: signal SIGABRT崩溃。
解决方法
移除显式类型声明:让Swift自动推断
@UIApplicationDelegateAdaptor变量的类型,避免强制类型转换冲突@main struct PlaygroundApp: App { // 移除: AppDelegate,依赖自动类型推断 @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { ContentView() } } } public class AppDelegate: NSObject, UIApplicationDelegate { static var orientationLock: UIInterfaceOrientationMask = .all public func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { AppDelegate.orientationLock } }通过UIApplication获取实例:如果需要访问自定义
AppDelegate的属性或方法,直接从UIApplication获取并强转,绕过代理类的包装问题// 在需要调用的位置添加 guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } // 例如访问orientationLock appDelegate.orientationLock = .portrait
内容的提问来源于stack exchange,提问作者tHatpart
相关产品推荐
相关产品推荐

