Swift JSON解码导致Xcode Playgrounds崩溃问题求助
Xcode Playgrounds JSON解码触发LLDB RPC服务器崩溃的解决办法
这个问题是Xcode Playgrounds与LLDB调试服务交互的已知bug——当你在同一执行流里用多行字符串字面量生成JSON数据并立即解码时,会触发RPC连接拒绝错误(Error Code 61),直接导致LLDB服务器崩溃,因此你根本无法执行到错误打印语句。而命令行环境没有调试层的额外交互逻辑,所以代码能正常运行。
你可以通过以下方式修复这个问题:
方法1:将解码逻辑封装到函数中
把解码操作放到独立函数里,避免在全局作用域直接执行解码,修改后的代码如下:
import Foundation struct Animals: Codable { let animals: [Animal] } struct Animal: Codable { let species: String let weight: Int } // 单独定义JSON字符串 let jsonString = """ { "animals": [ { "species": "rabbit", "weight": 3 }, { "species": "dog", "weight": 7 } ] } """ // 解码逻辑封装到函数 func decodeAnimals() { guard let jsonData = jsonString.data(using: .utf8) else { print("Invalid JSON") return } do { let animals = try JSONDecoder().decode(Animals.self, from: jsonData) print(animals) } catch { print(error) } } // 调用函数执行解码 decodeAnimals()
方法2:加载本地JSON文件
如果你的JSON内容较长,可以把它保存为本地.json文件,然后通过文件URL加载数据,绕开字符串字面量的问题:
import Foundation struct Animals: Codable { let animals: [Animal] } struct Animal: Codable { let species: String let weight: Int } guard let fileURL = Bundle.main.url(forResource: "animals", withExtension: "json"), let jsonData = try? Data(contentsOf: fileURL) else { print("Failed to load JSON file") exit(1) } do { let animals = try JSONDecoder().decode(Animals.self, from: jsonData) print(animals) } catch { print(error) }
其他临时解决方案
- 切换Playgrounds运行模式:点击编辑器右上角"Play"按钮旁的菜单,选择"Run My Code"而非"Live View"模式
- 更新Xcode到最新稳定版本,苹果可能在后续版本修复该调试交互bug
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

