Checking keyDown event.modifierFlags yields error

Im subclassing NSTextView and overriding keyDown. I want to detect command-key-combinations. Command-L, for example.

Apple’s documentation indicates that you simply and the modifier flags (in the passed NSEvent) with NSEventModifierFlags.CommandKeyMask.

  • Building Objective-C App with External Framework
  • Iterating through NSDictionary for null value
  • How can I get all supported screen resolutions on mac OSX Swift
  • Execute an Action when the Enter-Key is pressed in a NSTextField?
  • Get video NSData from ALAsset url iOS
  • Sorting two NSArrays together side by side
  • When I do so:

    let ck = NSEventModifierFlags.CommandKeyMask

    I receive an odd error:

    Binary operator '&' cannot be applied to two 'NSEventModifierFlags' operands.

    What’s the deal? This is swift 2.0, xcode 7.


    2 Solutions Collect From Internet About “Checking keyDown event.modifierFlags yields error”

    Apple’s documentation indicates that you simply and the modifier flags

    The documentation is still referring to C and Objective-C. Swift uses OptionSetType, which does not use bitwise operators for checking flags.

    Instead, use the contains() method to check for one or more flags:

        if theEvent.modifierFlags.contains(.CommandKeyMask) {
            NSLog("command key down")
        if theEvent.modifierFlags.contains(.AlternateKeyMask) {
            NSLog("option key down")
        if theEvent.modifierFlags.contains([.CommandKeyMask, .AlternateKeyMask]) {
            NSLog("command and option keys down")

    To check for a single key, use intersect to filter out any unwanted flags, then use == to check for a single flag:

        let modifierkeys = theEvent.modifierFlags.intersect(.DeviceIndependentModifierFlagsMask)
        if modifierkeys == .CommandKeyMask {
            NSLog("Only command key down")

    NSEventModifierFlags is an optionSet in Swift 2.0. You can use contain method to check it contains the command modifier key

    override func keyDown(theEvent:NSEvent) {
        if theEvent.characters == "l" && theEvent.modifierFlags.contains(.CommandKeyMask) {
            print("command-L pressed")