Last active
December 11, 2015 15:58
-
-
Save fluidsonic/6a8f1c1def2a92416519 to your computer and use it in GitHub Desktop.
Recursive Struct through Indirect Enum
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
struct Path: CustomStringConvertible { | |
private var hasParent = HasParent.No | |
var key: String | |
init(forKey key: String, inParent parent: Path? = nil) { | |
self.key = key | |
self.parent = parent | |
} | |
var description: String { | |
if let parent = parent { | |
return "\(parent).\(key)" | |
} | |
else { | |
return key | |
} | |
} | |
var parent: Path? { | |
get { | |
switch hasParent { | |
case .No: return nil | |
case let .Yes(parent): return parent | |
} | |
} | |
set { | |
if let parent = newValue { | |
hasParent = .Yes(parent) | |
} | |
else { | |
hasParent = .No | |
} | |
} | |
} | |
private enum HasParent { | |
case No | |
indirect case Yes(Path) | |
} | |
} | |
let level0 = Path(forKey: "level0") | |
let level1 = Path(forKey: "level1", inParent: level0) | |
let level2 = Path(forKey: "level2", inParent: level1) | |
let level3 = Path(forKey: "level3", inParent: level2) | |
print(level3) | |
// output: level0.level1.level2.level3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment