Skip to content

Instantly share code, notes, and snippets.

@cfilipov
cfilipov / SwiftGenericTrie.md
Last active July 21, 2016 00:49
Generic-Key Trie in Swift

Generic Trie in Swift

This is an attempt to implement a trie in Swift with a generic key. Instead of using just strings as keys, this trie can be keyed by any object that can generate its own prefixes. This is accomplished by using a protocol to define a trie key that can return a generator of Hashables. We need Hashables because the prefixes will be stored in a Dictionary.

Defining the Key Type

The TrieNode class will be a private implementation detail. It helps to separate the implementation into TrieNode and the wrapper for a few reasons:

  1. If we want to extend the trie to implement some common Swift collection protocols, many of those don't make sense for every node.
  2. We want references for nodes but the wrapper struct can help us simulate value semantics.