An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.


class NSMutableDictionary : NSDictionary


The NSMutableDictionary class declares the programmatic interface to objects that manage mutable associations of keys and values. It adds modification operations to the basic operations it inherits from NSDictionary.

NSMutableDictionary is “toll-free bridged” with its Core Foundation counterpart, CFMutableDictionary. See Toll-Free Bridging for more information on toll-free bridging.

Setting Values Using Subscripting

In addition to the provided instance methods, such as setObject(_:forKey:), you can access NSDictionary values by their keys using subscripting.

let value = "someValue"
mutableDictionary["someKey"] = value

Subclassing Notes

There should typically be little need to subclass NSMutableDictionary. If you do need to customize behavior, it is often better to consider composition rather than subclassing.

Methods to Override

In a subclass, you must override both of its primitive methods:

You must also override the primitive methods of the NSDictionary class.


Creating and Initializing a Mutable Dictionary

init(capacity: Int)

Initializes a newly allocated mutable dictionary, allocating enough memory to hold numItems entries.


Initializes a newly allocated mutable dictionary.

init(sharedKeySet: Any)

Creates a mutable dictionary which is optimized for dealing with a known set of keys.

Adding Entries to a Mutable Dictionary

func setObject(Any, forKey: NSCopying)

Adds a given key-value pair to the dictionary.

func setValue(Any?, forKey: String)

Adds a given key-value pair to the dictionary.

func addEntries(from: [AnyHashable : Any])

Adds to the receiving dictionary the entries from another dictionary.

func setDictionary([AnyHashable : Any])

Sets the contents of the receiving dictionary to entries in a given dictionary.

Removing Entries From a Mutable Dictionary

func removeObject(forKey: Any)

Removes a given key and its associated value from the dictionary.

func removeAllObjects()

Empties the dictionary of its entries.

func removeObjects(forKeys: [Any])

Removes from the dictionary entries specified by elements in a given array.

See Also


class NSDictionary

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software