I want to read a key from the input of the terminal, with readLine I have to press enter first, how do I get around this
Read single key from stdin
Swift does not have built-in support for this. Rather, you’re expected to use standard BSD constructs for putting the terminal into non-canonical mode. For example, if you build this code:
and then run it from Terminal and then type some characters, you’ll see output like this:
For more info on this, see the termios man page.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Code Block import Foundation func main() { let fd = STDIN_FILENO guard isatty(fd) != 0 else { fatalError() } var tio = termios() var ok = tcgetattr(fd, &tio) >= 0 guard ok else { fatalError() } tio.c_lflag &= ~UInt(ICANON | ECHO) ok = tcsetattr(fd, TCSANOW, &tio) >= 0 guard ok else { fatalError() } while true { var buf: UInt8 = 0 let readResult = read(fd, &buf, 1) if readResult < 0 { fatalError() } else if readResult == 0 { exit(EXIT_SUCCESS) } else { assert(readResult == 1) print(buf) } } } main()
and then run it from Terminal and then type some characters, you’ll see output like this:
Code Block % ./NonCanonTest 104 101 108 108 111 32 99 114 117 101 108 32 119 111 114 108 100
For more info on this, see the termios man page.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"