How to detect Delete key press in Swift?

question macOS swift
Ram Patra Published on August 14, 2020

Delete key press detection is slightly different than other keys. It uses NSDeleteCharacter like below:

event.charactersIgnoringModifiers == String(UnicodeScalar(NSDeleteCharacter)!) 

So, the complete code may look like:

NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
    if self.keyDown(with: $0) {
        return nil // needed to get rid of purr sound
    } else {
        return $0

private func keyDown(with event: NSEvent) -> Bool {
    if event.charactersIgnoringModifiers == String(UnicodeScalar(NSDeleteCharacter)!) {
    	print("Delete key presses!")
        return true
    } else {
    	return false
Ram Patra Published on August 14, 2020
Image placeholder

Keep reading

If this article was helpful, others might be too

question macOS swift August 6, 2020 How to keep an app's window always on top of others in Swift?

Before launching the window, just use the appropriate window level, and you’re done.

May 28, 2020 Best Mac Apps for Working From Home

For me personally, it is a mixed feeling working from home. On one hand, I have the flexibility with when to work and when not to but on the other hand, it is sometimes hard for me to find that fine line between work and life. There are days when I keep working even after office hours without realizing that I have got my life wife too :)

June 7, 2020 How to add Global Key Shortcuts to your macOS app using MASShortcut

Adding Global Keyboard Shortcuts to your macOS app can be a pain as there isn’t a Cocoa API for the same. You would have to rely on the old, most of which are deprecated, Carbon API.