2015-06-09 58 views
0

我到目前爲止這個聲明:多個參數

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"]] 

我想這樣做,但我不知道如何申報meals變量:

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] 

我想將第三個參數添加到字典數組中,即整數,因此每個OptionX都必須有2個參數:日期數組和一個整數。

我知道字典必須是鍵值,所以我想知道如何爲每個數組添加3個元素。我想我必須創建數組的數組?

回答

3

你可以使用一個元組,我會明確說明字典類型,以使事情更清楚一點:

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" 
} 

或者,你可以使用結構:

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" 
} 
+0

的感謝! @ABakerSmith – Ruben

+0

我在這一行中得到一個錯誤:let meals = [String:MealOption] = [「Option1」:MealOption(a:[「01-01-2015」,「05-02-2015」],b:2 )]'它說:「不能分配給這個表達式的結果」@ABakerSmith – Ruben

+0

對不起,我有一個額外的'='在那裏意外。我已經更新了我的答案。 – ABakerSmith