Search code examples
swiftxcodeterminalgetch

Xcode Swift Command Line Tool reads 1 char from keyboard without echo or need to press return


I need a function, like the old "getch()", in Objective C or Swift to read one single character from the keyboard without echo and without the nedd to press return after the character has been typed to make the function continue.

This is, I know, only interesting when programming command line tools, perhaps to make a selection or write an editor.


Solution

  • Here is the function for use with Swift, written in Swift:

    func GetKeyPress () -> Int
    {
        var key: Int = 0
        var c: cc_t = 0
        var cct = (c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c) // Set of 20 Special Characters
        var oldt: termios = termios(c_iflag: 0, c_oflag: 0, c_cflag: 0, c_lflag: 0, c_cc: cct, c_ispeed: 0, c_ospeed: 0)
    
        tcgetattr(STDIN_FILENO, &oldt) // 1473
        var newt = oldt
        newt.c_lflag = 1217  // Reset ICANON and Echo off
        tcsetattr( STDIN_FILENO, TCSANOW, &newt)
        key = Int(getchar())  // works like "getch()"
        tcsetattr( STDIN_FILENO, TCSANOW, &oldt)
        return key
    }