Last active
August 29, 2015 14:02
-
-
Save erica/9e573199411651d2825f to your computer and use it in GitHub Desktop.
Bag
This file contains hidden or 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
// | |
// 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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