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

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)

问题根源

  1. readLine()不兼容Playground环境:Xcode Playground不支持标准输入,readLine()会返回nil,强行用!强制解包必然触发崩溃。
  2. 参数冗余覆盖: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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:15:54