我有以下类型的字典:
{
"filter": {
"year_option": {
"2015": "2015",
"2016": "2016"
},
"month_option": {
"10": "Oct",
"11": "Nov",
"12": "Dec",
"01": "Jan",
"02": "Feb",
"03": "Mar",
"04": "Apr",
"05": "May",
"06": "Jun",
"07": "Jul",
"08": "Aug",
"09": "Sept"
}
}
}
这是来自 API
的响应。 字典
中的键可能因每个用户而异。那么有没有办法仅在键可用
时获取Dictionary
值?
最佳答案
当然,有办法。使用 if let
检查是否存在 key 。
例如:
if let key1 = yourDict["key1"] {
// do something with key1
}
使用您的示例:
if let filter = yourDict["filter"] as? [String: Any] {
if let yearOption = filter["year_option"] as? [String: String] {
// there is the year_option JSON
}
if let monthOption = filter["month_option"] as? [String:String] {
// there is the month option JSON
}
}
关于swift - 仅当键在字典中可用时才获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41118418/