how do I pipe input to a swift cli application

Asked on 08/01/2024

1 search

To pipe input to a Swift CLI application, you can use standard input (stdin) in your Swift code. Here's a simple example of how you can read from stdin in a Swift CLI application:

import Foundation

// Read input from stdin
if let input = readLine() {
    print("Received input: \(input)")
} else {
    print("No input received")
}

You can compile this Swift code into a binary and then run it from the terminal, piping input to it. For example:

echo "Hello, Swift CLI!" | ./your-swift-cli-app

This will output:

Received input: Hello, Swift CLI!

For more detailed examples and context, you might want to check out the session A Swift Tour: Explore Swift’s features and design, which discusses building command-line tools in Swift and using argument parsers.