编辑代码


// 树

class Node {
  var value: String // 父节点
  var children: [Node] = [] // 子节点
  weak var parent: Node? // 弱引用 避免爆内存

  init(value: String) {
    self.value = value
  }

  func add(child: Node) {
    children.append(child)
    child.parent = self
  }
}

// CustomStringConvertible协议
// 打印
extension Node: CustomStringConvertible {
  var description: String {
  var text = "\(value)"
    
    if !children.isEmpty {
      text += " {" + children.map { $0.description }.joined(separator: ", ") + "} "
    }
    return text
  }
}

// 搜索
extension Node {
  // 1
  func search(value: String) -> Node? {
    // 2
    if value == self.value {
      return self
    }
    // 3
    for child in children {
      if let found = child.search(value: value) {
        return found
      }
    }
    // 4
    return nil
  }
}



let beverages = Node(value: "beverages") // 类实例化时不是引用是复制
let beverages2 = beverages //只有当其赋值给其它变量时 才是引用 
beverages2.value = "1"  // 结构体不管是实例化还是赋值都保持复制

let hotBeverages = Node(value: "hot")
let coldBeverages = Node(value: "cold")

beverages.add(child: hotBeverages)
beverages.add(child: coldBeverages)
print(beverages)

// print(beverages.search(value: "cocoa")) // returns the "cocoa" node