Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bag
//
// Bag.swift
// CmdLineTest
//
// Created by Erica Sadun on 6/23/14.
// Copyright (c) 2014 Erica Sadun. All rights reserved.
//
import Foundation
class Bag<T: Hashable> {
var _storage = Dictionary<T, Int>()
// MARK: Init
init(_ items : T ...)
{
self.addItems(items)
}
init(items : Array<T>)
{
self.addItems(items)
}
// MARK: Add
func addItem(item : T)
{
if let count = _storage[item] {
_storage[item] = count + 1
} else {
_storage[item] = 1
}
}
func addItems(items : Array<T>)
{
for item in items
{
self.addItem(item)
}
}
func addItems(items : T...)
{
self.addItems(items)
}
// MARK: Remove
func removeItem(item: T) {
if let count = _storage[item]
{
if (count > 1) {
_storage[item] = count - 1
} else {
_storage.removeValueForKey(item)
}
}
}
func removeItems(items : Array<T>)
{
for item in items
{
self.removeItem(item)
}
}
func removeItems(items : T...)
{
self.removeItems(items)
}
// MARK: Utility
func countForItem(item: T) -> Int? {
return _storage[item]
}
func members() -> T[] {
return Array(_storage.keys)
}
}
extension Bag : Printable {
var description : String {
return _storage.description
}
}
struct BagGenerator<T:Hashable> : Generator{
var _backingGenerator : DictionaryGenerator<T, Int>
init(_ backingDictionary : Dictionary<T, Int>) {
_backingGenerator = backingDictionary.generate()
}
typealias Element = (T, Int)
mutating func next() -> (T, Int)? {
return _backingGenerator.next()
}
}
extension Bag : Sequence {
typealias GeneratorType = BagGenerator<T>
func generate() -> BagGenerator<T>{
return BagGenerator<T>(_storage)
}
}
@erica

This comment has been minimized.

Copy link
Owner Author

commented Jun 23, 2014

This has the advantage of extensibility to a 3-tuple, which is why the bag generator is structured as it is

@algal

This comment has been minimized.

Copy link

commented Jun 23, 2014

Do you mean by this that you could modify the BagGenerator so that BagGenerator.Element = (T, Int, SomethingElse) ?

@erica

This comment has been minimized.

Copy link
Owner Author

commented Jun 23, 2014

Yes -- although in v2, I changed it back because I finished writing up that kind of extension. This is now more about the bag and less about the tuple

@erica

This comment has been minimized.

Copy link
Owner Author

commented Jun 23, 2014

And voila, v2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.