2016-05-01 96 views
2

我正在嘗試從字典中檢索數據並將值分配給「城市」。我想使用information[1]["City"],但也會產生錯誤。另外,不知道是否需要在這裏打開可選項。從字典中檢索數據Swift

let locals = ["Jerry":["City": "Seattle", "Preference": "Adventurer"],"Emily":["City": "Boston", "Preference": "History Buff"]    


func matchTravellerWithLocal(location: String, type: String) -> String { 
    var message = " " 
    let locals = LocalsInformation().locals 
    for (name, information) in locals{ 
     let city = information["City"]! 
     print(city) 
     let preference = information["Preference"] 
     if city == location{ 
      message = "Meet your local: \(name), a local of \(city)" 
     }else{ 
      message = "Apologies, there aren't in \(city) on  LocalRetreat. Try again soon!" 
      break 
     } 
     if preference == type{ 
      message += "who is also a \(preference)" 
     } 
    } 
    return message 
} 

回答

2

你的當地人應該這樣定義的:

let locals: [[String: Dictionary<String, String>]] = [["Jerry":["City": "Seattle", "Preference": "Adventurer"]],["Emily":["City": "Boston", "Preference": "History Buff"]]] 

然後你就可以像訪問:

let jerry = locals[0]["Jerry"] 
+0

是的,我想下標的字典,[1]但它是說我不能爲類型'Int'的索引'Dictionary '類型的值下標 – leisdorf

+0

其他建議? – leisdorf

+0

@LEisdorfer我沒有編輯代碼。 – Ramis