Skip to content

Instantly share code, notes, and snippets.

@algal
Forked from erica/gist:9e573199411651d2825f
Last active August 29, 2015 14:02
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 algal/f64814fc5b307124e165 to your computer and use it in GitHub Desktop.
Save algal/f64814fc5b307124e165 to your computer and use it in GitHub Desktop.
class Bag<T: Hashable>: Sequence, Printable {
var _storage = Dictionary<T, Int>()
typealias GeneratorType = Dictionary<T,Int>.GeneratorType
func addItem(item: T) {
if let count = _storage[item] {
_storage[item] = count + 1
} else {
_storage[item] = 1
}
}
func removeItem(item: T) {
if let count = _storage[item]
{
if (count > 1) {
_storage[item] = count - 1
} else {
_storage.removeValueForKey(item)
}
}
}
func countOfItem(item: T) -> Int? {
return _storage[item]
}
func items() -> T[] {
return Array(_storage.keys)
}
func generate() -> GeneratorType {
return _storage.generate()
}
var description: String {
return _storage.description
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment