Last active
July 24, 2017 05:08
-
-
Save sebastienwindal/5c4a74453030dff2be1844f0a1f44a1a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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