Using Swift Extensions To Clean Up Our Code

init(rootValue: DataType) { self.root = NodeType(value: rootValue) } init(rootValue: DataType, leftTree: BST, rightTree: BST) { self.root = NodeType(value: rootValue, left: leftTree.root, right: rightTree.root) } private init(rootNode: NodeType) { self.root = rootNode } func add(_ data: DataType) -> Bool { return false } func contains(_ data: DataType) -> Bool { return false } func find(_ data: DataType) -> DataType?.{ return nil } func delete(_ data: DataType) -> DataType?.{ return nil } func remove(_ data:DataType) -> Bool { return false } private final class BSN<DataType: Comparable>: BinaryNode { var value: DataType var parent: BSN<DataType>?.var left: BSN<DataType>?.var right: BSN<DataType>?.init(value: DataType) { self.value = value } init(value: DataType, left: BSN?, right: BSN?) { self.value = value self.left = left self.right = right } }}I don’t want to be that guy, but… this looks terrible..And just imagine when there are actual implementations of the SearchTree protocol methods..A Search Tree is a structure that lends itself well for recursive method implementations, which means that the functions that are specified in the protocol will act as wrappers around yet another method, doubling the method declarations we need.The main thing with this layout is that it makes it very difficult for us to get an overview..Where do we start looking if we want to change one of the SearchTree protocol implementations?.Where do we put new methods if we want to be able to find them quickly later on?Step 3: Refactoring Using ExtensionsExtensions were not really designed to solve any readability problems..They were designed to solve a whole other problem set, but the fact that we can use them this way is a nice side effect..Let’s give it a go!class BinarySearchTree<DataType: Comparable> { fileprivate typealias NodeType = BinarySearchNode<DataType> private var root: NodeType?. More details

Leave a Reply