Skip to content

Instantly share code, notes, and snippets.

@sebastienwindal
Last active July 24, 2017 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastienwindal/5c4a74453030dff2be1844f0a1f44a1a to your computer and use it in GitHub Desktop.
Save sebastienwindal/5c4a74453030dff2be1844f0a1f44a1a to your computer and use it in GitHub Desktop.
public struct DictArray<Key: Hashable, Value> : CustomDebugStringConvertible {
private typealias Bucket = [Value]
private var buckets: [ Key: Bucket ]
init() {
buckets = [:]
}
public mutating func add(value:Value, key:Key) {
var bucket:Bucket
if let existingBucket = buckets[key] {
bucket = existingBucket
} else {
bucket = Bucket()
}
bucket.append(value)
buckets[key] = bucket
}
@discardableResult public mutating func pop(at key:Key) -> Value? {
guard var existingBucket = buckets[key],
let element:Value = existingBucket.removeLast() else {
return nil
}
if existingBucket.count == 0 {
// remove bucket
buckets.removeValue(forKey: key)
} else {
buckets[key] = existingBucket
}
return element
}
public func hasValue(at key:Key) -> Bool {
return buckets[key] != nil
}
public var debugDescription: String {
var str = "["
for k in buckets.keys {
str += "\n \(k) => ["
for e in buckets[k]! {
str += "\(e), "
}
str += "]"
}
str += "\n]"
return str
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment