Skip to main content

Checking Modifier Keys in Swift

·1 min

Checking for modifier keys (Command, Control, Option, and Shift) when handling events is different in Objective-C and Swift. In Objective-C you perform a bitwise AND operation to check if modifier keys were held down. In Swift you check if the event’s modifier flags contains the specific modifier key.

The following example demonstrates how to check the modifier keys for a mouse down event in Swift:

override func mouseDown(with event: NSEvent) {
    if event.modifierFlags.contains(.command) {
        // Handle command-click
    } 
    else if event.modifierFlags.contains(.control) {
        // Handle control-click
    }
    else {
        // Handle standard mouse click
    }
}