Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 367
lionserdar Avatar asked Jun 03 '14 18:06

lionserdar


People also ask

Can a dictionary have different types?

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.

Are Swift dictionaries value types?

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.

How do you define a type in Swift?

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 .


1 Answers

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.

like image 99
Maciej Jastrzebski Avatar answered Sep 29 '22 10:09

Maciej Jastrzebski