问题
I already know how to get the input from user keyboard.
I can use the readLine()
method or
let input = FileHandle.standardInput
let inputData = input.availableData
var text = String(data: inputData, encoding: .utf8)
But the two methods get also when the user press an arrow key button. I would like to filter the input in order to remove these data. I want that the user can write something, maybe go back with the left arrow key, change something and insert the data without problem. Thanks!
回答1:
What you are looking for is the “line editing feature” which is provided by libedit on macOS.
In order to use it from a Swift command line tool, you need to
#include <readline/readline.h>
in the bridging header file,- add “libedit.tbd” to the “Link Binary With Libraries” section in the “Build Phases” of your target.
Here is a minimal example Swift program:
while let cString = readline("prompt>") {
let line = String(cString: cString)
free(cString)
print(line)
}
Important: You have to run this in the Terminal, it won't work properly in the Xcode debugger console.
Each input line can be edited before entering Return, similar to what you can do in the Terminal. And with
while let cString = readline("prompt>") {
add_history(cString) // <-- ADDED
let line = String(cString: cString)
free(cString)
print(line)
}
you can even use the up/down arrow keys to navigate to previously entered lines.
For more information, call man 3 readline
in the Terminal.
Here is a possible helper function:
func readlineHelper(prompt: String? = nil, addToHistory: Bool = false) -> String? {
guard let cString = readline(prompt) else { return nil }
defer { free(cString) }
if addToHistory { add_history(cString) }
return(String(cString: cString))
}
Usage example:
while let line = readlineHelper(addToHistory: true) {
print(line)
}
来源:https://stackoverflow.com/questions/52794640/allow-line-editing-when-reading-input-from-the-command-line