Skip to content

Instantly share code, notes, and snippets.

@amayatsky
Last active March 31, 2020 11:01
Show Gist options
  • Save amayatsky/6b5bb2edc383d174b92557b997e58f49 to your computer and use it in GitHub Desktop.
Save amayatsky/6b5bb2edc383d174b92557b997e58f49 to your computer and use it in GitHub Desktop.
Reusable Swift Extension to Make Any Class Hashable
protocol ObjectIdentifierHashable : class, Hashable {
}
extension ObjectIdentifierHashable {
static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs === rhs
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
}
class Tree : ObjectIdentifierHashable, CustomStringConvertible, {
var text: String
let left: Tree?
let right: Tree?
var link: Tree?
init(text: String, left: Tree? = nil, right: Tree? = nil) {
self.text = text
self.left = left
self.right = right
}
var description: String {
let leftDesc = left != nil ? left!.text : "null"
let rightDesc = right != nil ? right!.text : "null"
let linkDesc = link != nil ? link!.text : "null"
return "text: \(text), left: \(leftDesc), right: \(rightDesc), link: \(linkDesc)"
}
}
func copyWithLinks(_ tree: Tree?) -> Tree? {
var copiedNodes: [Tree:Tree] = [:] // note how we use Tree as a Key ;)
func copy(_ oldTree: Tree?) -> Tree? {
if let oldTree = oldTree {
let newTree = Tree(text: "c_" + oldTree.text, left: copy(oldTree.left), right: copy(oldTree.right))
copiedNodes[oldTree] = newTree
return newTree
} else {
return nil
}
}
let treeCopy = copy(tree)
for (oldTree, newTree) in copiedNodes {
if let oldLink = oldTree.link {
newTree.link = copiedNodes[oldLink]
}
}
return treeCopy
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment