I think you could use C API in swift to do that.
C code is from https://stackoverflow.com/a/1798833/1261661
This is just a swift version.
import Foundation
var old = termios()
var new = termios()
tcgetattr(STDIN_FILENO, &old)
new = old
new.c_lflag &= ~(UInt(ICANON))
new.c_lflag &= ~(UInt(ECHO))
tcsetattr(STDIN_FILENO, TCSANOW, &new)
while true {
    let c = getchar()
    if c == 113 {
        // quit on 'q'
        break
    } else {
        print(c)
    }
}
tcsetattr(STDIN_FILENO, TCSANOW, &old)
NSEvent.addGlobalMonitorForEvents can get all the key events too
but it require user's permission.
import Cocoa
import Foundation
@discardableResult
func acquirePrivileges() -> Bool {
    
    let accessEnabled = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary)
    
    if accessEnabled != true {
        print("You need to enable the keylogger in the System Prefrences")
    }
    
    return accessEnabled
}
class AppDelegate: NSObject, NSApplicationDelegate {
    private var monitor: Any?
    func applicationDidFinishLaunching(_ notification: Notification) {
        acquirePrivileges()
        monitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { event in
            print(event)
        }
    }
}
print(Bundle.main)
// Turn off echo of TTY
var old = termios()
var new = termios()
tcgetattr(STDIN_FILENO, &old)
new = old
new.c_lflag &= ~(UInt(ICANON))
new.c_lflag &= ~(UInt(ECHO))
tcsetattr(STDIN_FILENO, TCSANOW, &new)
let appDelegate = AppDelegate()
NSApplication.shared.delegate = appDelegate
NSApp.activate(ignoringOtherApps: true)
NSApp.run()
// restore tty
tcsetattr(STDIN_FILENO, TCSANOW, &old)
You can also take a look at this library, https://github.com/SkrewEverything/Swift-Keylogger
I think it is another interesting way to do the job.