title: Handling keyboard events in AppKit with Swift
body: <p>I have a custom NSView subclass that needs to handle some keyboard events. In Objective-C, I might handle it like this:</p>
  
  <pre><code>-(void)keyDown:(NSEvent *)event
  {
      unichar ch = [[event charactersIgnoringModifiers] characterAtIndex:0];
  
      if (ch == NSUpArrowFunctionKey &amp;&amp; (event.modifierFlags &amp; NSCommandKeyMask)) {
          // Scroll to top
          return;
      }
      else if (ch == NSDownArrowFunctionKey &amp;&amp; (event.modifierFlags &amp; NSCommandKeyMask)) {
          // Scroll to bottom
          return;
      }
  
      switch (ch) {
          case NSRightArrowFunctionKey:
              // Select the current row
              return;
          case ' ':
              // Scroll down one page
              return;
          default:
              break;
      }
  
      [super keyDown:event];
  }
  </code></pre>
  
  <p>In Swift, however,<code>characterAtIndex:</code> returns a <code>unichar</code>, while <code>NSUpArrowFunctionKey: Int</code> and <code>" ": String</code> (or <code>Character</code>). It's not clear to me how to convert a unichar to a <code>String</code> or <code>Character</code>.</p>
  
  <p>I got this working, but it feels like an ugly workaround. Is there a better way?</p>
  
  <pre><code>func keyDown(theEvent: NSEvent) {
      let char = Int(theEvent.charactersIgnoringModifiers.utf16[0])  // &lt;----- This seems ugly
      let hasCommand = (theEvent.modifierFlags &amp; .CommandKeyMask).value != 0
  
      switch char {
  
          case NSUpArrowFunctionKey where hasCommand == true:
              // Scroll to top
              break
  
          case NSDownArrowFunctionKey where hasCommand == true:
              // Scroll to bottom
              break
  
          case NSRightArrowFunctionKey where hasCommand == true:
              // Select the current row
              break
  
          case Int(" ".utf16[0]):   //  &lt;---- Surely there's a better way of doing this?
              // Scroll down one page
              break
  
          default:
              super.keyDown(theEvent)
      }
  }
  </code></pre>