Multiple parameters in a Dictionary

115 views Asked by At

I have this declaration so far:

var meals : [String : Array<String>]

meals = ["Option1": ["01-01-2015","05-02-2015"],
         "Option2": ["05-01-2015","10-04-2015"],
         "Option3": ["03-02-2015", "07-07-2015"]]

I would like to do something like this, but I don't know how to declare the meals variable:

meals = ["Option1": ["01-01-2015","05-02-2015"], 2
         "Option2": ["05-01-2015","10-04-2015"], 2
         "Option3": ["03-02-2015", "07-07-2015", "09-08-2015"], 3]

I would like to add the third parameter to the array of dictionaries, that is an integer, so every OptionX has to have 2 parameters: an array of dates, and an integer.

I know that a dictionary has to be Key-Value, so I'm wondering how to add 3 elements for each array. I guess that I must create arrays of arrays?

1

There are 1 answers

3
ABakerSmith On BEST ANSWER

You could use a tuple, I'll explicitly state the dictionary type to make things a bit clearer:

let meals: [String: ([String], Int)] = ["Option1": (["01-01-2015","05-02-2015"], 2),
                                        "Option2": (["05-01-2015","10-04-2015"], 2),
                                        "Option3": (["03-02-2015", "07-07-2015", "09-08-2015"], 3)]

if let option1 = meals["Option1"] {
    println(option1.0) // Prints: "[01-01-2015, 05-02-2015]"
    println(option1.1) // Prints: "2"
}

Alternatively, you could use a struct:

struct MealOption {
    // More descriptive variable names would be a good idea here...
    let a: [String]
    let b: Int
}

let meals: [String: MealOption] = ["Option1": MealOption(a: ["01-01-2015","05-02-2015"], b: 2)]

if let option1 = meals["Option1"] {
    println(option1.a) // Prints: "[01-01-2015, 05-02-2015]"
    println(option1.b) // Prints: "2"
}