我正在尝试编写一个在字典中搜索字符串的函数,如果找到,则保留该条目,否则从数据源中删除该条目。
这是我的初始数据源结构
[String: Array<Dictionary<String, AnyObject>>]
示例数据来源:
[
A: [
[id: 1, name: "Android"],
[id: 22, name: "Apple"],
[id: 3, name: "Apricot"]
],
B: [
[id: 33, name: "Bat"],
[id: 45, name: "Breeze"]
]
]
下面是我的函数的样子,这里ltrToCompare
是我的搜索字符串,
func getFilteredData(data : [String: Array<Dictionary<String, AnyObject>>], ltrToCompare : String) -> [String: Array<Dictionary<String, AnyObject>>] {
// For keeping the filtered result
var filteredData = [String: Array<Dictionary<String, AnyObject>>]()
// Looping through parent array
for (letter, arr) in data {
// Filters the internal array, below code works when arr is an array containing strings ie., [String], doesn't work for Array<Dictionary<String, AnyObject>>
let filter = arr.filter() {
return $0.lowercaseString.rangeOfString(ltrToCompare.lowercaseString) != nil
}
// Checks whether the inner array filtering returns any element
if (filter.count != 0) {
filteredData.append((letter, filter));
}
}
return filteredData
}
如果我的数据结构为[String: Array<String>]
而不是[String: Array<Dictionary<String, AnyObject>>]
非常感谢任何帮助。
答案 0 :(得分:2)
import Foundation
let data:[String: Array<Dictionary<String, AnyObject>>] = [
"A": [
["id": 1, "name": "Android"],
["id": 22, "name": "Apple"],
["id": 3, "name": "Apricot"]
],
"B": [
["id": 33, "name": "Bat"],
["id": 45, "name": "Breeze"]
]
]
func getFilteredData(data : [String: Array<Dictionary<String, AnyObject>>], ltrToCompare : String) -> [String: Array<Dictionary<String, AnyObject>>] {
var filteredData = [String: Array<Dictionary<String, AnyObject>>]()
for (letter, arr) in data {
let filter = arr.filter() {
return $0["name"]?.lowercaseString.rangeOfString(ltrToCompare.lowercaseString) != nil
}
if (filter.count != 0) {
filteredData[letter] = filter
}
}
return filteredData
}
let res = getFilteredData(data, ltrToCompare: "Andro")
print(res) // ["A": [["id": 1, "name": Android]]]
let res2 = getFilteredData(data, ltrToCompare: "aP")
print(res2) // ["A": [["id": 22, "name": Apple], ["id": 3, "name": Apricot]]]