How do I implement a trie in Swift?

A trie (pronounced "try") is a type of search tree that is used to store dynamic sets or associative arrays where the keys are usually strings. It allows for efficient retrieval of keys in a dataset, making it particularly useful for tasks like autocomplete and spell-checking.

Trie Implementation in Swift

Below is a simple implementation of a trie in Swift:

// Trie Node Definition class TrieNode { var children: [Character: TrieNode] = [:] var isEndOfWord: Bool = false } class Trie { private var root: TrieNode init() { root = TrieNode() } // Insert a word into the trie func insert(_ word: String) { var node = root for char in word { if node.children[char] == nil { node.children[char] = TrieNode() } node = node.children[char]! } node.isEndOfWord = true } // Search for a word in the trie func search(_ word: String) -> Bool { var node = root for char in word { if let nextNode = node.children[char] { node = nextNode } else { return false } } return node.isEndOfWord } // Check if any word in the trie starts with the given prefix func startsWith(_ prefix: String) -> Bool { var node = root for char in prefix { if let nextNode = node.children[char] { node = nextNode } else { return false } } return true } }

Trie Swift Data Structures Autocomplete Spell-check Search