Using `indirect` modifier for `struct` properties

Hi @xwu sorry for the late response, I've been a bit swamped these days.

But to me in this particular case some workarounds were better than others, as your example of using a final class, wouldn't be a good choice for me because(although it was not production code) I wanted to have full value semantics and define a set of API's that has mutating/non-mutating, explicitly specify an inout when I wanted a mutable parameter... and have the compiler helping when try violate those rules. So a final class wouldn't be a good choice. I didn't explore much of the other possibilities e.g. a @ Indirect property wrapper which would be just as ideal as the workaround I end up with. But in short, I just wanted to take full advantage of value semantics and have the compiler help me not do something I shouldn't like mutating a node in someplace I explicitly didn't tell is allowed. Also for readability when I wanted to see an & when I can have a node be modified inside a method. Just this little/minor things made me not go for classes.

At the end I went for something like @typesanitizer mentioned

struct BinaryTreeNode<E: Comparable> {
  var element: E
  var count: Int = 1
  private var childs: [BinaryTreeNode<E>?] = [nil, nil]
  
  var left: BinaryTreeNode<E>? {
    get { childs[0] }
    set { childs[0] = newValue }
  }
  
  var right: BinaryTreeNode<E>? {
    get { childs[1] }
    set { childs[1] = newValue }
  }
  
  init(element: E) {
    self.element = element
  }
}

It was really simple and serve its purpose well. That's one of the reasons I thought that although this would be nice to have, I think it wouldn't add significant improvements to the language since the cases where we would need something like this would be very specific and limited. And also, it is easy to find another solution when we stumble in one of those cases...

So those were my points @xwu hope it helps in some way :)

2 Likes