简体   繁体   中英

Swift dictionary with array as value

How do you declare a dictionary that has an array as the value? Is this even possible?

Yes

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

In fact, you don't even need the explicit type declaration if you assign an initial value in place. It can go as simple as:

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
 var dictionary : [String:[AnyObject]]

 var dictionary2 = [String:[AnyObject]]()

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

If you want to store for example an array of strings:

var dict: [String: [String]]

or without syntactic sugar:

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

Dictionaries, like arrays and more generally whatever uses generics, can handle anything that is a swift type, including tuples, closures, dictionaries, dictionaries of dictionaries, arrays of dictionaries, etc. - unless conditions are specified for the generic type (for instance, a dictionary key can be any type that implements the Hashable protocol), and in that case types must conform to the constraints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM