Swift dictionary with array as value

How do you declare a dictionary that has an array? Is it possible?

+5
source share
3 answers

Yes

let myDictionary: [String: [Int]] = ["Hello": [1, 2, 3], "World": [4, 5, 6]] 

In fact, you do not even need an explicit type declaration if you assign an initial value in place. It could be simple:

 let myDictionary = ["Hello": [1, 2, 3], "World": [4, 5, 6]] 

To use the value:

 println(myDictionary["Hello"][0]) // Print 1 println(myDictionary["World"][0]) // Print 4 
+9
source

If you want to save, for example, an array of strings:

 var dict: [String: [String]] 

or without syntactic sugar:

 var dict: Dictionary<String, Array<String>> 

Dictionaries, such as arrays and, in general, everything that uses generics, can handle everything that is a fast type, including tuples, closures, dictionaries, dictionary dictionaries, arrays of dictionaries, etc. - if the conditions for the type type are not specified (for example, the dictionary key can be any type that implements the Hashable protocol), in which case the types must comply with the restrictions.

0
source
  var dictionary : [String:[AnyObject]] var dictionary2 = [String:[AnyObject]]() 

You can change AnyObject for any class or use it as AnyObject if you don't know the class that will be in the array.

0
source

Source: https://habr.com/ru/post/1207425/


All Articles