title: Swift: How to compare Optional in "if" clause
body: <p>I'm practising Swift by building trees with array.</p>
  
  <p>I have a class Node. Each node has an ID and a parent ID. The parent ID could be nil, if the node is a top-level node. So I made parent ID Optional.</p>
  
  <p>Then I manually (for testing purpose) created an array of nodes, which contains multiple trees. So there are multiple nodes with parent ID = nil.</p>
  
  <p>Then I created a function which find nodes by their parent ID.</p>
  
  <p>Compiler didn't complain. However when run in iPhone simulator (I tried to display the nodes in a tableview), a message displays <strong>at the if clause in the function</strong>:</p>
  
  <blockquote>
    <p>fatal error: unexpectedly found nil while unwrapping an Optional value</p>
  </blockquote>
  
  <p>Please help. Thanks.</p>
  
  <p>Here is the code.
  (for my own habit I write ";" at the end of each line.)</p>
  
  <pre><code>class Node {
    var id:Int;
    var parent:Int!;
    init(id:Int, parent:Int!) {
      self.id = id;
      self.parent = parent;
    }
  }
  
  var allNodes = [
    Node(id:1, parent: nil),
    Node(id:2, parent: nil),
    Node(id:3, parent: 1),
    Node(id:4, parent: 1),
    Node(id:5, parent: 2),
    Node(id:6, parent: 2),
    Node(id:7, parent: 2)
  ];
  
  func findNodes(parent:Int!) -&gt; [Node] {
    var arr:[Node] = [];
    for node in allNodes {
      if node.parent == parent! {
        // if I use "if node.parent == parent" without the "!" it gives me the same error
        arr.append(node);
      }
    }
    return arr;
  }
  
  let nodes = self.findNodes(nil);
  // called in tableview functions.
  // same message if I use findNodes(1).
  </code></pre>