diff --git a/Package.swift b/Package.swift index 5f85cae..900e322 100644 --- a/Package.swift +++ b/Package.swift @@ -13,13 +13,18 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/apple/swift-docc-plugin.git", from: "1.3.0") + .package(url: "https://github.com/apple/swift-docc-plugin.git", from: "1.3.0"), + .package(url: "https://github.com/apple/swift-collections.git", .upToNextMajor(from: "1.1.1")) ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and products from dependencies. .target( - name: "SwiftTrie"), + name: "SwiftTrie", + dependencies: [ + .product(name: "OrderedCollections", package: "swift-collections") + ] + ), .testTarget( name: "SwiftTrieTests", dependencies: ["SwiftTrie"]) diff --git a/Sources/SwiftTrie/Trie.swift b/Sources/SwiftTrie/Trie.swift index ebf4030..c5f818e 100644 --- a/Sources/SwiftTrie/Trie.swift +++ b/Sources/SwiftTrie/Trie.swift @@ -6,6 +6,7 @@ // import Foundation +import OrderedCollections /// Trie is a tree data structure of all the substring permutations of a collection of strings /// optimized for searching for values of type V. @@ -22,11 +23,11 @@ import Foundation /// /// See the article on [Trie](https://en.wikipedia.org/wiki/Trie) on Wikipedia. public class Trie { - private var children: [Character: Trie] = [:] + private var children = OrderedDictionary() /// Separate exact matches from strict substrings so that exact matches appear first in returned results. - private var exactMatchValues = Set() - private var substringMatchValues = Set() + private var exactMatchValues = OrderedSet() + private var substringMatchValues = OrderedSet() private var parent: Trie? @@ -79,7 +80,7 @@ public extension Trie { } // Perform breadth-first search from matching branch and collect values from all descendants. - var substringMatches = Set(currentNode.substringMatchValues) + var substringMatches = OrderedSet(currentNode.substringMatchValues) var queue = Array(currentNode.children.values) while !queue.isEmpty { @@ -149,7 +150,7 @@ public extension Trie { } if keyIndex == 0 { - currentNode.exactMatchValues.insert(value) + currentNode.exactMatchValues.append(value) // If includeNonPrefixedMatches is true, the first character of the key can be the only root branch // and we terminate the loop early. @@ -157,7 +158,7 @@ public extension Trie { break } } else { - currentNode.substringMatchValues.insert(value) + currentNode.substringMatchValues.append(value) } } }