How do I put different types in a dictionary in the Swift Language?

dictionary, swift

Solution

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`.

Problem

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` and `NSMutableDictionary` 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?

Original source