A lightweight collection of key-value pairs.
- Xcode 10.2+
- Swift Standard Library
Key instance when you need an ordered collection of key-value pairs and don’t require the fast key lookup that the
Dictionary type provides. Unlike key-value pairs in a true dictionary, neither the key nor the value of a
Key instance must conform to the
You initialize a
Key instance using a Swift dictionary literal. Besides maintaining the order of the original dictionary literal,
Key also allows duplicates keys. For example:
Some operations that are efficient on a dictionary are slower when using
Key. In particular, to find the value matching a key, you must search through every element of the collection. The call to
first in the following example must traverse the whole collection to find the element that matches the predicate:
Key-Value Pairs as a Function Parameter
When calling a function with a
Key parameter, you can pass a Swift dictionary literal without causing a
Dictionary to be created. This capability can be especially important when the order of elements in the literal is significant.
For example, you could create an
Int structure that holds a list of two-integer tuples and use an initializer that accepts a
When you’re ready to create a new
Int instance, use a dictionary literal as the parameter to the
Int initializer. The
Key instance preserves the order of the elements as passed.