2

I'm trying to add two numbers in Swift and print its sum

import Foundation

func solveMefirst(firstNo: Int , secondNo: Int) -> Int {
    return firstNo + secondNo
}

let num1 = readLine()
let num2 = readLine()

var IntNum1 = Int(num1!) ** Execution was interrupted, reason: EXC_BAD_INSTRUCTION (Code=EXC_l386_INVOP, subcode=0x0). **
var IntNum2 = Int(num2!)

let sum = solveMefirst(IntNum1!, secondNo: IntNum2!)
print(sum)

But unfortunately this error comes out and stops the execution in playground.

Execution was interrupted, reason: EXC_BAD_INSTRUCTION (Code=EXC_l386_INVOP, subcode=0x0).

enter image description here

Could not understand, what is wrong in this?

UPDATE

Also please explain how to run this command line program in playground?

How can I take input from playground??.

Vinod Rathod
  • 732
  • 3
  • 8
  • 23
  • `num1` and `num2` are nil as you can clearly see in the output - what is supposed to happen when you unwrap them? – luk2302 Feb 11 '16 at 19:04
  • 1
    You should read [What does an exclamation mark mean in the Swift language?](http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language), it will help a lot. – Eric Aya Feb 11 '16 at 19:14
  • @EricD. can u please explain how to take STDIN input in playground – Vinod Rathod Feb 11 '16 at 21:19

2 Answers2

2

I ran it using command line. I think you are using play ground but you didn't take input for num1 and num2. After running the project take input for number 1 then press enter. Then take input for number two and press enter. It will give you the desired result. Your code is working fine. I run it here.

Output of Command Line Based Project

Shehzad Ali
  • 1,846
  • 10
  • 16
  • Positive suggestions are always appreciated :) – Shehzad Ali Feb 11 '16 at 19:16
  • can you tell me how to run this code in playgrounds? – Vinod Rathod Feb 11 '16 at 21:09
  • If you want to take input from user its better to switch on console based application in Xcode. Furthermore its mentioned in Raywenderlich tutorial that playground doesn't allow input from user: [Reference Tutorial of RayWenderlich:](http://www.raywenderlich.com/114173/learn-to-code-ios-apps-with-swift-tutorial-2-your-first-project) – Shehzad Ali Feb 12 '16 at 06:58
1

It crashes because you force a nil value which results in an error; As you can read on the left num1= nil. It don't know what it is supposed to be but there is the error. Because when you try to force a value to num1(that's what "!" does) it crashes because num1 has no value.

Eric
  • 1,210
  • 8
  • 25