Swift代码在Xcode Playground运行报错,求问题排查与修复
Swift计算器代码崩溃问题修复
问题
Xcode Playground中运行给定Swift代码时触发崩溃,报错信息如下:
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
__lldb_expr_1/MyPlayground.playground:4: Fatal error: Unexpectedly found nil while unwrapping an Optional value
原代码:
func calculator(a:Int, b:Int) { let a = Int(readLine()!)! //First input let b = Int(readLine()!)! //Second input add(n1: a, n2: b) subtract(n1: a, n2: b) multiply(n1: a, n2: b) divide(n1: a, n2: b) } //Write your code below this line to make the above function calls work. func add(n1:Int, n2:Int){ print(n1+n2) } func subtract(n1:Int, n2:Int){ print(n1-n2) } func multiply(n1:Int, n2:Int){ print(n1*n2) } func divide(n1:Int, n2:Int){ let a1 = Double(n1) let a2 = Double(n2) print(a1 / a2) } calculator(a:3, b:4)
问题根源
readLine()不兼容Playground环境:Xcode Playground不支持标准输入,readLine()会返回nil,强行用!强制解包必然触发崩溃。- 参数冗余覆盖:
calculator函数已接收a、b作为入参,但内部又重新定义同名常量,完全忽略传入的参数,属于无效逻辑。
修复代码
func calculator(a: Int, b: Int) { add(n1: a, n2: b) subtract(n1: a, n2: b) multiply(n1: a, n2: b) divide(n1: a, n2: b) } func add(n1: Int, n2: Int) { print(n1 + n2) } func subtract(n1: Int, n2: Int) { print(n1 - n2) } func multiply(n1: Int, n2: Int) { print(n1 * n2) } func divide(n1: Int, n2: Int) { // 新增除数非零校验,避免除以0崩溃 guard n2 != 0 else { print("除数不能为0") return } print(Double(n1) / Double(n2)) } calculator(a: 3, b: 4)
修复说明
- 移除函数内的
readLine()调用,直接使用传入的参数,匹配函数设计意图。 - 为
divide函数增加除数非零判断,避免潜在的除以0错误。 - 运行后输出结果:
7 -1 12 0.75
内容的提问来源于stack exchange,提问作者metomaru
相关产品推荐
相关产品推荐

