2

I'm creating a command line application which requires the user to press a single key to input something.

I've heard of the readLine() function, but the user needs to press return in order to enter it and it allows for >1 character inputs. Also, the readLine function stalls the thread it's called on, which I'd like to avoid (so it should be an event/interrupt with a handler closure).

Something like this is what I'm looking for:

var characters = [Character]()
keyPressEvent(handler: { characters.append($0) })
// ... rest of code using 'characters'

How do I implement that in actual Swift? Thanks!

Smally
  • 1,556
  • 1
  • 8
  • 27
  • Command line applications typically don't do this. They are like a conversation, you say something (print), then the user says something (input), then you parse that input and say something back. – Kevin Apr 01 '22 at 11:38
  • 1
    How about the "press any key to continue" prompts? I assume those are like `readLine()`, but don't take the `return` key to publish the input. – Smally Apr 01 '22 at 11:40
  • Something like this? https://stackoverflow.com/questions/59795706/getch-equivalent-in-swift-read-a-single-character-from-stdin-without-a-newlin – Kevin Apr 01 '22 at 11:41
  • 1
    I played around with it and it looks quite promising (my application makes use of `RunLoop.main.run()` and had to remove that for it to pick up on any stdin changes, which makes it hacky). Thanks! – Smally Apr 01 '22 at 14:10

0 Answers0