title: Swift on OS X: How to access the current CGContext for drawing in -[NSView drawRect:]
body: <h1>Setup:</h1>
  
  <p>Xcode 6.1<br>
  OS X 10.9.5<br>
  <strong>Swift Mac</strong> Document-based Application target</p>
  
  <h1>Question:</h1>
  
  <p>I am using <strong>Swift</strong> to make a Cocoa <strong>Mac</strong> app (<em>NOT iOS</em>!). I have a custom <code>NSView</code> subclass. I'd like to override <code>-drawRect:</code>, and access the current <code>CGContext</code> to do some drawing using the CoreGraphics APIs.</p>
  
  <p>However, I can't seem to access the current <code>CGContext</code> in Swift (something I've done hundreds of times in ObjC). Here's my code:</p>
  
  <pre><code>import Cocoa
  
  class Canvas: NSView {
      override func drawRect(dirtyRect: CGRect) {
          if let ctx: CGContext! = NSGraphicsContext.currentContext()?.CGContext {
              // do drawing
          }
      }
  }
  </code></pre>
  
  <p>When I run, I get an immediate crash on the first line of my <code>drawRect</code> implementation:</p>
  
  <pre><code>-[NSWindowGraphicsContext CGContext]: unrecognized selector sent to instance 0x60800005e840
  </code></pre>
  
  <p>What am I doing wrong? How do I fetch the current <code>CGContext</code> for drawing in Swift?</p>
  
  <h1>NOTE:</h1>
  
  <p>I definitely want to use the CoreGraphics API. Unless using the CoreGraphics API in Swift is entirely impossible, please do not respond with suggestions on how to use AppKit drawing APIs instead (I don't care if they are easier). I want to know how to use CoreGraphics from Swift on OS X.</p>