Last active
November 4, 2021 08:40
-
-
Save zats/c39dbd9b0017fb3b77dd37be744cf474 to your computer and use it in GitHub Desktop.
Recursive structures in Swift without Box classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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