Created
February 12, 2017 21:07
-
-
Save ignazioc/936b9b98aa218053cd8c337e0225bf65 to your computer and use it in GitHub Desktop.
Example of indirect enum with Swift3
This file contains 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
import Cocoa | |
enum DataStructure { | |
case node(value: String) | |
indirect case tree(left: DataStructure, right: DataStructure) | |
} | |
let nodeA = DataStructure.node(value: "A") | |
let nodeB = DataStructure.node(value: "B") | |
let treeA = DataStructure.tree(left: nodeA, right: nodeB) | |
let treeB = DataStructure.tree(left: .node(value: "C"), right: .node(value: "D")) | |
let forest = DataStructure.tree(left: treeA, right: treeB) | |
func visitTree(_ dataStructure: DataStructure) -> String { | |
switch dataStructure { | |
case let .node(value: v): | |
return "[\(v)]" | |
case let .tree(left: l, right: r): | |
return "( \(visitTree(l)) \(visitTree(r)) )" | |
} | |
} | |
visitTree(nodeA) | |
visitTree(nodeB) | |
visitTree(treeA) | |
visitTree(forest) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment