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

This Tree is far from complete and needs lots of functionality. For instance, we may need to check whether the Tree contains a specific value. To be able to do this, we need to add the following method to our Tree:

static func contains(_ key: Element, tree: Tree<Element>) -> Bool {     switch tree {     case .leaf(let element):         return key == element     case node(let lhs, let rhs):         return contains(key, tree: lhs) || contains(key, tree: rhs)     } } 

We can test the contains method as follows:

let isFound = Tree.contains("First", tree: functionalTree)  print(isFound) // prints true 

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