title: Swift Tree Structure, encoding and accessing nodes
body: <p>I am having trouble figuring out why the following does not run. The goal is to create a tree structure with reference types that can be saved to a json file, but the following playground code does not run.</p>
  <p>The root node has a nil parent, but I thought the encoder ignored nil values. In my app I get an EXC_BAD_ACCESS. Does this need to be done with structs instead of classes, and if so, is there a way to access a particular node without traversing the entire tree? Any help appreciated.</p>
  <pre><code>import Cocoa
  
  final class Node: Codable {
      var id: UUID
      var data: [MyData]
      var children: [Node]
      var parent: Node? = nil
      
      init() {
          self.id = UUID()
          self.data = []
          self.children = []
      }
      
      func add(data: MyData) {
          data.parent = self
          self.data.append(data)
      }
      
      func add(child: Node) {
          child.parent = self
          self.children.append(child)
      }
  }
  
  final class MyData: Codable {
      var id: UUID
      var label: String
      var value: String
      var parent: Node? = nil
      
      init(label: String, value: String) {
          self.id = UUID()
          self.label = label
          self.value = value
      }
  }
  
  var root = Node()
  root.add(data: MyData(label: &quot;label 1&quot;, value: &quot;value 1&quot;))
  root.add(data: MyData(label: &quot;label 2&quot;, value: &quot;value 2&quot;))
  var child = Node()
  child.add(data: MyData(label: &quot;label 3&quot;, value: &quot;value 3&quot;))
  root.add(child: child)
  let encoder = JSONEncoder()
  encoder.outputFormatting = .prettyPrinted
  let json = try encoder.encode(root)
  print(String(data: json, encoding: .utf8)!)
  
  </code></pre>