DEV Community

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

Posted on

5 2

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more