@@ -38,13 +38,14 @@ public class Node : CustomStringConvertible {
3838
3939 public init ( newParent: Node ? = nil ) {
4040 self . parent = newParent
41+ parent? . addAndSetParent ( child: self )
4142 }
4243
4344 public func getChilds ( ) -> [ Node ] {
4445 return self . childs
4546 }
4647
47- public func add ( child : Node ) {
48+ public func addAndSetParent ( child : Node ) {
4849 self . childs. append ( child)
4950 child. parent = self
5051 }
@@ -61,7 +62,26 @@ public class Node : CustomStringConvertible {
6162 }
6263 return self . childs [ at]
6364 }
64-
65+ func removeChild ( node : Node ) -> Node ? {
66+ for (offset, maybeSelf) in self . childs. enumerated ( ) {
67+ if node === maybeSelf { // self reference? not compare content or whatever
68+ self . childs. remove ( at: offset)
69+ return self
70+ }
71+ }
72+ return nil
73+ }
74+ func removeChildAndRemoveParent ( node : Node ) -> Node ? {
75+ for (offset, maybeSelf) in self . childs. enumerated ( ) {
76+ if node === maybeSelf { // self reference? not compare content or whatever
77+ self . childs. remove ( at: offset)
78+ node. parent = nil
79+ return self
80+ }
81+ }
82+ return nil
83+ }
84+
6585 public func isLeaf ( ) -> Bool {
6686 return childs. isEmpty
6787 }
@@ -98,5 +118,20 @@ public class Node : CustomStringConvertible {
98118 public func getParent ( ) -> Node ? {
99119 return self . parent
100120 }
121+
122+ /// Set new parent to the node.
123+ ///
124+ /// This function remove if existing the parent and itself from parent child list and then add self to the parent child list and set the parent here
125+ ///
126+ /// - Parameters:
127+ /// - Parameter with newParent to set
128+ /// - Returns self
129+ public func setParent ( with newParent : Node ? ) -> Node {
130+ if let current = self . parent {
131+ current. removeChild ( node: self ) ? . parent = nil
132+ }
133+ self . parent? . addAndSetParent ( child: self )
134+ return self
135+ }
101136}
102137
0 commit comments