The NSCounted​Set class declares the programmatic interface to a mutable, unordered collection of distinct objects. A counted set is also known as a bag.


Each distinct object inserted into an NSCounted​Set object has a counter associated with it. NSCounted​Set keeps track of the number of times objects are inserted and requires that objects be removed the same number of times. Thus, there is only one instance of an object in an NSSet object even if the object has been added to the set multiple times. The count method defined by the superclass NSSet has special significance; it returns the number of distinct objects, not the total number of times objects are represented in the set. The NSSet and NSMutable​Set classes are provided for static and dynamic sets, respectively, whose elements are distinct.

While NSCounted​Set and CFBag are not toll-free bridged, they provide similar functionality. For more information about CFBag, see the CFBag.

Subclassing Notes

Because NSCounted​Set is not a class cluster, it does not have primitive methods that provide the basis for its implementation. In general, there should be little need for subclassing.

Methods to Override

If you subclass NSCounted​Set, you must override any method of which you want to change the behavior.

If you change the primitive behavior of an NSCounted​Set, for instance if you change how objects are stored, you must override all of the affected methods. These include:

If you change the primitive behavior, you must also override the primitive methods of NSSet and NSMutable​Set.


Initializing a Counted Set

init(array:​ [Any])

Returns a counted set object initialized with the contents of a given array.

init(set:​ Set<Any​Hashable>)

Returns a counted set object initialized with the contents of a given set.

init(capacity:​ Int)

Returns a counted set object initialized with enough memory to hold a given number of objects.

Adding and Removing Entries

func add(Any)

Adds a given object to the set.

func remove(Any)

Removes a given object from the set.

Examining a Counted Set

func count(for:​ Any)

Returns the count associated with a given object in the set.

func object​Enumerator()

Returns an enumerator object that lets you access each object in the set once, independent of its count.