-
-
Save algal/f64814fc5b307124e165 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
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