How do I implement a generic trie in Swift?

A generic trie implementation in Swift allows you to efficiently store a dynamic set of strings and perform prefix searches. Below is a simple implementation of a generic trie that can handle any type of comparable keys.

class TrieNode { var children: [T: TrieNode] = [:] var isEndOfWord: Bool = false } class Trie { private let root = TrieNode() func insert(word: [T]) { var currentNode = root for char in word { if currentNode.children[char] == nil { currentNode.children[char] = TrieNode() } currentNode = currentNode.children[char]! } currentNode.isEndOfWord = true } func search(word: [T]) -> Bool { var currentNode = root for char in word { guard let nextNode = currentNode.children[char] else { return false } currentNode = nextNode } return currentNode.isEndOfWord } func startsWith(prefix: [T]) -> Bool { var currentNode = root for char in prefix { guard let nextNode = currentNode.children[char] else { return false } currentNode = nextNode } return true } } // Example Usage let trie = Trie() trie.insert(word: Array("apple".characters)) print(trie.search(word: Array("apple".characters))) // true print(trie.startsWith(prefix: Array("app".characters))) // true

generic trie Swift trie prefix search data structure Swift programming