Class

NSDictionary

The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. Use this class or its subclass NSMutable​Dictionary when you need a convenient and efficient way to retrieve data associated with an arbitrary key. NSDictionary creates static dictionaries, and NSMutable​Dictionary creates dynamic dictionaries. (For convenience, the term dictionary refers to any instance of one of these classes without specifying its exact class membership.)

Overview

A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key’s value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by is​Equal(_:​)). In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see Accessing Object Properties). Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull.

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

Creating NSDictionary Objects Using Dictionary Literals

In addition to the provided initializers, such as init(objects:​for​Keys:​), you can create an NSDictionary object using a dictionary literal.

let dictionary: NSDictionary = [
    "anObject" : someObject,
    "helloString" : "Hello, World!",
    "magicNumber" : 42,
    "aValue" : someValue
]

In Objective-C, the compiler generates code that makes an underlying call to the init(objects:​for​Keys:​count:​) method.

id objects[] = { someObject, @"Hello, World!", @42, someValue };
id keys[] = { @"anObject", @"helloString", @"magicNumber", @"aValue" };
NSUInteger count = sizeof(objects) / sizeof(id);
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
                                                       forKeys:keys
                                                         count:count];

Unlike dictionary​With​Objects​And​Keys:​ and other initializers, dictionary literals specify entries in key-value order. You should not terminate the list of objects with nil when using this literal syntax, and in fact nil is an invalid value. For more information about object literals in Objective-C, see Working with Objects in Programming with Objective-C.

In Swift, the NSDictionary class conforms to the DictionaryLiteralConvertible protocol, which allows it to be initialized with dictionary literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 3.1).

Accessing Values Using Subscripting

In addition to the provided instance methods, such as object(for​Key:​), you can access NSDictionary values by their keys using subscripting.

let value = dictionary["helloString"]

Enumerating Entries Using for-in Loops

In addition to the provided instance methods, such as enumerate​Keys​And​Objects(_:​), you can enumerate NSDictionary entries using for-in loops.

for (key, value) in dictionary {
    print("Value: \(value) for key: \(key)")
}

In Objective-C, NSDictionary conforms to the NSFast​Enumeration protocol.

In Swift, NSDictionary conforms to the SequenceType protocol.

Subclassing Notes

You generally shouldn’t need to subclass NSDictionary. Custom behavior can usually be achieved through composition rather than subclassing.

Methods to Override

If you do need to subclass NSDictionary, take into account that it is a Class cluster. Any subclass must override the following primitive methods:

The other methods of NSDictionary operate by invoking one or more of these primitives. The non-primitive methods provide convenient ways of accessing multiple entries at once.

Alternatives to Subclassing

Before making a custom class of NSDictionary, investigate NSMap​Table and the corresponding Core Foundation type, CFDictionary. Because NSDictionary and CFDictionary are “toll-free bridged,” you can substitute a CFDictionary object for a NSDictionary object in your code (with appropriate casting). Although they are corresponding types, CFDictionary and NSDictionary do not have identical interfaces or implementations, and you can sometimes do things with CFDictionary that you cannot easily do with NSDictionary.

If the behavior you want to add supplements that of the existing class, you could write a category on NSDictionary. Keep in mind, however, that this category will be in effect for all instances of NSDictionary that you use, and this might have unintended consequences. Alternatively, you could use composition to achieve the desired behavior.

Symbols

Initializing an NSDictionary Instance

init()

Initializes a newly allocated dictionary.

init?(contents​Of​File:​ String)

Initializes a newly allocated dictionary using the keys and values found in a file at a given path.

init?(contents​Of:​ URL)

Initializes a newly allocated dictionary using the keys and values found at a given URL.

init(dictionary:​ [Any​Hashable :​ Any])

Initializes a newly allocated dictionary by placing in it the keys and values contained in another given dictionary.

init(dictionary:​ [Any​Hashable :​ Any], copy​Items:​ Bool)

Initializes a newly allocated dictionary using the objects contained in another given dictionary.

init(objects:​ [Any], for​Keys:​ [NSCopying])

Initializes a newly allocated dictionary with entries constructed from the contents of the objects and keys arrays.

Creating Key Sets for Shared-Key Optimized Dictionaries

class func shared​Key​Set(for​Keys:​ [NSCopying])

Creates a shared key set object for the specified keys.

Counting Entries

var count:​ Int

The number of entries in the dictionary

Comparing Dictionaries

func is​Equal(to:​ [Any​Hashable :​ Any])

Returns a Boolean value that indicates whether the contents of the receiving dictionary are equal to the contents of another given dictionary.

Accessing Keys and Values

var all​Keys:​ [Any]

A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries

func all​Keys(for:​ Any)

Returns a new array containing the keys corresponding to all occurrences of a given object in the dictionary.

var all​Values:​ [Any]

A new array containing the dictionary’s values, or an empty array if the dictionary has no entries

func object(for​Key:​ Any)

Returns the value associated with a given key.

subscript(NSCopying)

Returns the value associated with a given key.

func objects(for​Keys:​ [Any], not​Found​Marker:​ Any)

Returns the set of objects from the dictionary that corresponds to the specified keys as an NSArray.

func value(for​Key:​ String)

Returns the value associated with a given key.

Enumerating Dictionaries

func object​Enumerator()

Returns an enumerator object that lets you access each value in the dictionary.

Sorting Dictionaries

func keys​Sorted​By​Value(using:​ Selector)

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values.

func keys​Sorted​By​Value(comparator:​ (Any, Any) -> Comparison​Result)

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block.

func keys​Sorted​By​Value(options:​ NSSort​Options = [], using​Comparator:​ (Any, Any) -> Comparison​Result)

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block and a specified set of options.

Filtering Dictionaries

func keys​Of​Entries(passing​Test:​ (Any, Any, Unsafe​Mutable​Pointer<Obj​CBool>) -> Bool)

Returns the set of keys whose corresponding value satisfies a constraint described by a block object.

func keys​Of​Entries(options:​ NSEnumeration​Options = [], passing​Test:​ (Any, Any, Unsafe​Mutable​Pointer<Obj​CBool>) -> Bool)

Returns the set of keys whose corresponding value satisfies a constraint described by a block object.

Storing Dictionaries

func write(to​File:​ String, atomically:​ Bool)

Writes a property list representation of the contents of the dictionary to a given path.

func write(to:​ URL, atomically:​ Bool)

Writes a property list representation of the contents of the dictionary to a given URL.

Accessing File Attributes

func file​Creation​Date()

Returns the value for the NSFile​Creation​Date key.

func file​Extension​Hidden()

Returns the value for the NSFile​Extension​Hidden key.

func file​Group​Owner​Account​ID()

Returns the value for the NSFile​Group​Owner​Account​ID key.

func file​Group​Owner​Account​Name()

Returns the value for the NSFile​Group​Owner​Account​Name key.

func file​HFSCreator​Code()

Returns the value for the NSFile​HFSCreator​Code key.

func file​HFSType​Code()

Returns the value for the NSFile​HFSType​Code key.

func file​Is​Append​Only()

Returns the value for the NSFile​Append​Only key.

func file​Is​Immutable()

Returns the value for the NSFile​Immutable key.

func file​Modification​Date()

Returns the value for the key NSFile​Modification​Date.

func file​Owner​Account​ID()

Returns the value for the NSFile​Owner​Account​ID key.

func file​Owner​Account​Name()

Returns the value for the key NSFile​Owner​Account​Name.

func file​Posix​Permissions()

Returns the value for the key NSFile​Posix​Permissions.

func file​Size()

Returns the value for the key NSFile​Size.

func file​System​File​Number()

Returns the value for the key NSFile​System​File​Number.

func file​System​Number()

Returns the value for the key NSFile​System​Number.

func file​Type()

Returns the value for the key NSFile​Type.

Creating a Description

var description:​ String

A string that represents the contents of the dictionary, formatted as a property list

var description​In​Strings​File​Format:​ String

A string that represents the contents of the dictionary, formatted in .strings file format

func description(with​Locale:​ Any?)

Returns a string object that represents the contents of the dictionary, formatted as a property list.

func description(with​Locale:​ Any?, indent:​ Int)

Returns a string object that represents the contents of the dictionary, formatted as a property list.

Initializers

init?(coder:​ NSCoder)
init(dictionary:​ NSDictionary)

Initializes a newly allocated dictionary and adds to it objects from another given dictionary.

init(dictionary​Literal:​ (Any, Any)...)

Instance Methods

func key​Enumerator()
func make​Iterator()

Return an iterator over the elements of this sequence.

Subscripts