I’m looking to take the community temperature about adding CountedSet
to Swift Foundation/Standard Library. This is a Swift native version of NSCountedSet
with the following preliminary design:
/// An unordered collection of unique hashable elements that
/// may appear more than once in the collection.
///
/// Each distinct value inserted into an `CountedSet`
/// has an associated counter. `CountedSet` keeps
/// track of the number of times each value is inserted.
/// That value must be removed the same number
/// of times.
///
/// Like `Set`, each `CountedSet` contains one entry for
/// each value, even when a value has been added multiple
/// times. The `count` method for both `Set` and `CountedSet`
/// returns the total number of values stored in each set.
/// A `CountedSet` does _not_ return the total number of times
/// each value is represented in the set.
///
/// New counted sets can be constructed from arrays.
/// Assign an array literal to a variable or constant
/// of the `CountedSet` type.
///
/// let quiver: CountedSet<Arrow> = [Arrow.iron, Arrow.elven, Arrow. elven]
/// if let count = quiver[.iron] {
/// print("There are \(count) iron arrows in your quiver")
/// }
Counted sets (also called bag
s, see CFBag
) are often used in game development for tracking player inventories. They are useful for any task where one keeps count of unique values in a collection. They provide support for standard set operations (subsets, contains, insert, remove, union, intersection, etc). They can be iterated over (without guarantees of order), providing (value, count)
tuples. Some function, likely a subscript, returns the number of times a value has been inserted into the set.
The type is easily implemented by wrapping a dictionary.
What are your thoughts about adding this type to Swift?