Instantly share code, notes, and snippets.

What would you like to do?
Recursive, generic enums in Swift
protocol TreeLike {}
enum Tree<T> : TreeLike {
case Leaf(@autoclosure () -> T)
case Node(TreeLike, TreeLike)
func node<T>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
return Tree.Node(left, right)
let tree : Tree<Int> = node(node(.Leaf(2), .Leaf(3)), node(.Leaf(5), .Leaf(7)))
func searchInTree<T: Equatable>(search: T, tree: Tree<T>) -> Bool {
switch tree {
case .Leaf(let x):
return x() == search
case .Node(let l as Tree<T>, let r as Tree<T>):
return searchInTree(search, l) || searchInTree(search, r)
return false
searchInTree(7, tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment