Search code examples
swiftxcode

Why does this piece of code gives error and couldn't print result?


Can anyone point out the problem with the code below? I couldn't get it run properly in Xcode playground, any help would be greatly appreciated.

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)

Error:

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

Expect it to simply print result of add, subtract, multiply, and divide.


Solution

  • The error was that you created useless constants in which you did not pass values. The correct way to do this is to pass a value in the parameters of a function when you call it

    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)
          
        }
        
        //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)
        }