title: Most elegant way to compare two optionals in Swift
body: <p>I have two <code>AnyObject?</code> variables that I would like to compare for reference equality:</p>
  
  <pre><code>var oldValue: AnyObject?
  var newValue: AnyObject?
  ...
  if oldValue != newValue {
      changed = true
  }
  </code></pre>
  
  <p>This doesn't work though, as I apparently cannot compare two optionals directly. I want the behavior as if I were comparing <code>id</code>s in Objective-C, that is:</p>
  
  <ul>
  <li><code>true</code> if both are <code>nil</code></li>
  <li><code>true</code> if both have a value and the values are also equal</li>
  <li><code>false</code> otherwise</li>
  </ul>
  
  <p>Is there an elegant way to write this in Swift (ideally without having to write a custom extension)?</p>
  
  <p>This is the best I've come up with:</p>
  
  <pre><code>if !(oldValue != nil &amp;&amp; newValue != nil &amp;&amp; oldValue == newValue)
  </code></pre>
  
  <p>Not very pretty. :(</p>