DEV Community

Cover image for Reading from the Standard Input (stdin) in Swift
Rithvik
Rithvik

Posted on

Reading from the Standard Input (stdin) in Swift

There are many situations where we need to read input from StdIn. For instance, this is how inputs are provided in competitive programming websites such as Hackerrank.

Reading from StdIn

readLine() function is used to read the input from the user.

readLine(strippingNewLine: Bool)
Enter fullscreen mode Exit fullscreen mode

Usually strippingNewLine is set to true, So that it will identify newline newline characters and character combinations are not a part of the input. Else, they will also be considered as the input.

And print() function is used to write the output to StdIn.

Reading string from StdIn

let str = readLine(strippingNewline: true)!
Enter fullscreen mode Exit fullscreen mode

It will be fine to force unwrap the String if we are sure about the situation else it may leads to crash.

Reading Int from StdIn

let str = Int(readLine(strippingNewline: true)!)!
Enter fullscreen mode Exit fullscreen mode

Reading array of String from StdIn

let array = (readLine(strippingNewline: true))?.split {$0 == " "}.map (String.init)
print(array!)
Enter fullscreen mode Exit fullscreen mode

Reading array of Int from StdIn

import Foundation
var arr = readLine()!.components(separatedBy: " ").map{ (a: String)->(Int) in
    return Int(a)!
}
print(array!)
Enter fullscreen mode Exit fullscreen mode

Testing

readline() returns nil in Playgrounds. So, in order to use this function we need to create Command Line Tool application.

File -> New -> Project.. (or simply ⇧⌘N) -> macOS -> Command Line Tool.

After creating the project we can use it just as Playgrounds.

Top comments (0)