Skip to content

Commit feeabb9

Browse files
authored
Merge pull request kodecocodes#687 from adborbas/master
HashTable CustomStringConvertible conformance in extension
2 parents acac45f + 2924b2d commit feeabb9

File tree

1 file changed

+20
-18
lines changed

1 file changed

+20
-18
lines changed

Hash Table/HashTable.playground/Sources/HashTable.swift

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
Insert: O(1) O(n)
3131
Delete: O(1) O(n)
3232
*/
33-
public struct HashTable<Key: Hashable, Value>: CustomStringConvertible {
33+
public struct HashTable<Key: Hashable, Value> {
3434
private typealias Element = (key: Key, value: Value)
3535
private typealias Bucket = [Element]
3636
private var buckets: [Bucket]
@@ -41,23 +41,6 @@ public struct HashTable<Key: Hashable, Value>: CustomStringConvertible {
4141
/// A Boolean value that indicates whether the hash table is empty.
4242
public var isEmpty: Bool { return count == 0 }
4343

44-
/// A string that represents the contents of the hash table.
45-
public var description: String {
46-
let pairs = buckets.flatMap { b in b.map { e in "\(e.key) = \(e.value)" } }
47-
return pairs.joined(separator: ", ")
48-
}
49-
50-
/// A string that represents the contents of
51-
/// the hash table, suitable for debugging.
52-
public var debugDescription: String {
53-
var str = ""
54-
for (i, bucket) in buckets.enumerated() {
55-
let pairs = bucket.map { e in "\(e.key) = \(e.value)" }
56-
str += "bucket \(i): " + pairs.joined(separator: ", ") + "\n"
57-
}
58-
return str
59-
}
60-
6144
/**
6245
Create a hash table with the given capacity.
6346
*/
@@ -151,3 +134,22 @@ public struct HashTable<Key: Hashable, Value>: CustomStringConvertible {
151134
return abs(key.hashValue) % buckets.count
152135
}
153136
}
137+
138+
extension HashTable: CustomStringConvertible {
139+
/// A string that represents the contents of the hash table.
140+
public var description: String {
141+
let pairs = buckets.flatMap { b in b.map { e in "\(e.key) = \(e.value)" } }
142+
return pairs.joined(separator: ", ")
143+
}
144+
145+
/// A string that represents the contents of
146+
/// the hash table, suitable for debugging.
147+
public var debugDescription: String {
148+
var str = ""
149+
for (i, bucket) in buckets.enumerated() {
150+
let pairs = bucket.map { e in "\(e.key) = \(e.value)" }
151+
str += "bucket \(i): " + pairs.joined(separator: ", ") + "\n"
152+
}
153+
return str
154+
}
155+
}

0 commit comments

Comments
 (0)