swiftxcodemacoscommand-line-tool

Swift Command Line Tool - Read multiple lines


I know the readLine() method, but if copy paste a text with more than one lines, only the first line will be retrieved.

I would like to retrieve all the text that the user copy pastes.

Is it possible ?


Solution

  • You can call readLine() in a loop and exit the loop in a predefined way

    var input: [String] = []
    
    print("Enter text, finish by entering Q")
    while let line = readLine(strippingNewline: true) {
        if line.lowercased() == "q" { break }
        input.append(line)
    }
    
    print(input)
    

    Example

    Enter text, finish by entering Q
    a
    b
    c
    q
    ["a", "b", "c"]
    Program ended with exit code: 0