Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take STDIN in Swift playground

I know that to program in STDIN and STDOUT, we need to make an command line project in Xcode. But how do I take a standard input in playground.

Whenever I try to run such code in playground

var input = readLine()!

I always get this error

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

Is it possible to take STDIN in playground or not?

UPDATE

I know this error is because of nil input variable but want to know how to overcome this nil value.

like image 276
Vinod Rathod Avatar asked Feb 13 '16 13:02

Vinod Rathod


1 Answers

Fixed Solution for SWIFT 3

To make it work, Create a new command line tool project.

Go to "File" -> "New" -> "Project" -> "macOS" -> "Command Line Tool".

import Foundation

print("Hello, World!")


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

func input() -> String {
    let keyboard = FileHandle.standardInput
    let inputData = keyboard.availableData
    return NSString(data: inputData, encoding:String.Encoding.utf8.rawValue) as! String
}

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

var IntNum1 = Int(num1!)
var IntNum2 = Int(num2!)

print("Addition of numbers is :  \(solveMefirst(firstNo: IntNum1!, secondNo: IntNum2!))")

And run the project using CMD + R

like image 55
MANISH PATHAK Avatar answered Sep 20 '22 06:09

MANISH PATHAK