Swift only allows a dictionary to contain a single type.
Here's the definition that is taken from the Swift book:
A dictionary is a container that stores multiple values of the same type
[...]
They differ from Objective-C’s
NSDictionary
andNSMutableDictionary
classes, which can use any kind of object as their keys and values and do not provide any information about the nature of these objects.
If that’s the case then how are we going to create nested dictionaries?
Imagine we have a plist
that holds String, Array and Dictionary items in it . If I’m allowed to hold only the same of type of items (either string, array etc.) then how am I going to use different types of items stored in the plist?
How do I put different types in the same dictionary in Swift?
One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.
In Swift, Array, String, and Dictionary are all value types. They behave much like a simple int value in C, acting as a unique instance of that data. You don't need to do anything special — such as making an explicit copy — to prevent other code from modifying that data behind your back.
In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it's defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass .
You can achieve plist-like nested structures using Any
type for dictionary values which is Swift's somewhat counterpart to Objective-C's id
type but can also hold value types.
var response = Dictionary<String, Any>() response["user"] = ["Login": "Power Ranger", "Password": "Mighty Morfin'"] response["status"] = 200
EDIT:
Any
seems to be better than AnyObject
because in the above code response["status"]
is of type Swift.Int
, while using value type of AnyObject
it is __NSCFNumber
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With