How to get STDIN on a Swift Playground

I know that for programming in STDIN and STDOUT we need to create a command line project in Xcode. But how do I take the standard entrance to the playground.

Whenever I try to run such code on the playground

var input = readLine()! 

I always get this error

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

Is it possible to take STDIN in the playground or not?

UPDATE

I know this error is related to the nil input variable, but you want to know how to overcome this nil value.

+6
source share
5 answers

Fixed solution for SWIFT 3

To make it work, create a new command line tool tool.

Go to “File” → “Create” → “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

+3
source

Try using optional chaining :

 if let input = readLine() { print("Input: \(input)") } else { print("No input.") } 
+2
source

To get input from the command line, for example Console.ReadLine ... Chalkers has the following solution.

 func input() -> String { var keyboard = NSFileHandle.fileHandleWithStandardInput() var inputData = keyboard.availableData return NSString(data: inputData, encoding:NSUTF8StringEncoding) as! String } 

please ask if it does not work Vinod.

+1
source

The playground cannot read input from the commend line.

You can use the custom function readLine () and the global input variable, each element of the input array represents a line:

 import Foundation var currentLine = 0 let input = ["5", "5 6 3"] func readLine() -> String? { if currentLine < input.endIndex { let line = input[currentLine] currentLine += 1 return line } else { return nil } } let firstLine = readLine() // 5 let secondLine = readLine() // 5 6 3 let thirdLine = readLine() // nil 
+1
source

Switch to

New> Project> Macros> Command Line Tool

then you can apply:

let value1: String?

 value1 = readLine() print(value ?? "") 

"" for default

-1
source

All Articles