我有数组,结构是:
var data = [["name" : "Piter", "pubDate" = "01"], ["name" : "Tomas", "pubDate" : "02"], ["name" : "Troy", "pubDate" : "03"]]
var newData = [[String:String]]?
现在我想检查是否有例如“pubDate”= 01,如果是,我想将此行(此行中的所有数据)添加到新表中。我做这样的事情:
for _ in data{
if data[indexPath.item]["pubDate"] == "01"{
newData!.append(data[indexPath.item])
}
}
但我的代码不起作用。你有什么想法,我怎样才能找到我需要的值并将整行添加到新数组中?
答案 0 :(得分:1)
您可以使用filter
方法轻松完成此操作:
let newData = data.filter { $0["pubDate"] == "01" }
无需循环,简单的单行。
答案 1 :(得分:1)
您的代码中存在拼写错误:
["name" : "Piter", "pubDate" = "01"]
应该是:
["name" : "Piter", "pubDate" : "01"]
我在这里有一个有效的解决方案:
let data = [["name" : "Piter", "pubDate" : "01"], ["name" : "Tomas", "pubDate" : "02"], ["name" : "Troy", "pubDate" : "03"]]
var newData = [[String:String]]()
for dictionary in data {
if dictionary["pubDate"] == "01" {
newData.append(dictionary)
}
}
print(newData);
答案 2 :(得分:0)
你可以像这样枚举一个字典数组
let dataArray:Array<Dictionary<String,String>> = [["name" : "Piter", "pubDate" : "01"], ["name" : "Tomas", "pubDate" : "02"], ["name" : "Troy", "pubDate" : "03"]]
var newData = [String:String]()
for dict in dataArray{
for (key,value) in dict{
if value == "01"{
newData[key] = value
print(newData)
}
}
}
希望能解决你的问题