Skip to content

Instantly share code, notes, and snippets.

@zats
Last active November 4, 2021 08:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zats/c39dbd9b0017fb3b77dd37be744cf474 to your computer and use it in GitHub Desktop.
Save zats/c39dbd9b0017fb3b77dd37be744cf474 to your computer and use it in GitHub Desktop.
Recursive structures in Swift without Box classes
struct Node<T> { // error: recursive value type 'Node<T>' is not allowed
var child: Node?
var value: T
init(value: T, child: Node? = nil) {
self.value = value
self.child = child
}
}
struct Node<T> {
private var _child: [Node]?
var child: Node? {
set {
_child = newValue.map{[$0]}
}
get {
return _child?.first
}
}
var value: T
init(value: T, child: Node? = nil) {
_child = child.map{ [$0] }
self.value = value
}
}
// Usage:
var root = Node(value: "a")
let child = Node(value: "b", child: Node(value: "c"))
root.child = child
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment