Xcode调试器处理Swift异常时高亮错误代码行问题求解
问题根因
Xcode 高亮错误行不正确是两个原因共同导致的:
- 你当前直接将错误抛到了命令行项目的顶层,没有手动捕获,Swift 运行时处理未捕获的顶层错误时,只会将错误定位到运行时的统一错误入口,不会关联到你的业务代码调用位置。
- 你的
testEq函数没有记录调用方的位置信息,无法将错误和实际调用testEq的代码行绑定。
调整方案
方案1:直接在测试函数内触发崩溃(最简适配)
利用Swift内置的#file、#line宏自动获取调用位置,在判断相等失败时直接调用带位置参数的fatalError,Xcode会直接将错误高亮在实际调用testEq的代码行,修改后代码如下:
enum TestFailure : Error { case testEqFailure(_ msg: String) } func testEq<E:Equatable>(_ actual: E, _ expected: E, file: StaticString = #file, line: UInt = #line) throws { if actual == expected { return } print("Test failed") print("Actual Result : \(actual)") print("Expected Result: \(expected)") // 传入调用位置触发崩溃,Xcode会直接定位到对应行 fatalError("Test Values were not equal", file: file, line: line) } try testEq(1,1) try testEq(7,8)
方案2:保留throw逻辑,手动捕获顶层错误
如果你需要保留错误抛出的逻辑做自定义处理,可以将位置信息存入错误枚举,同时在顶层添加do-catch包裹所有测试调用,修改后代码如下:
enum TestFailure : Error { // 错误枚举新增位置参数存储 case testEqFailure(_ msg: String, file: StaticString, line: UInt) } func testEq<E:Equatable>(_ actual: E, _ expected: E, file: StaticString = #file, line: UInt = #line) throws { if actual == expected { return } print("Test failed at \(file):\(line)") print("Actual Result : \(actual)") print("Expected Result: \(expected)") throw TestFailure.testEqFailure("Test Values were not equal", file: file, line: line) } // 顶层统一捕获错误,避免错误漏到Swift运行时 do { try testEq(1,1) try testEq(7,8) } catch let error as TestFailure { switch error { case .testEqFailure(let msg, let file, let line): fatalError(msg, file: file, line: line) } }
内容的提问来源于stack exchange,提问作者Mike Cargal
相关产品推荐
相关产品推荐

