O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The contains method

Additionally, our contains method requires to be modified as it will search only in leaves. Let's improve this, assuming that our Tree is a BST:

static func contains(_ item: Element, tree: BST<Element>) -> Bool {     switch tree {     case .leaf:         return false     case .node(let lhs, let element, let rhs):         if item < element {             return contains(item, tree: lhs)         } else if item > element {             return contains(item, tree: rhs)         }         return true     } } 

This method searches for a specific element and returns true if it finds it in node.

The following presents an example usage of this method:

let isFound = BST.contains(9, tree: functionalBST) 

The isFound variable is going to be true in this case.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required