【问题标题】:Filter Dictionary with a case insensitive search使用不区分大小写的搜索过滤字典
【发布时间】:2017-01-19 23:24:59
【问题描述】:

这是关于如何Filter a Dictionary 的后续问题,只有我需要过滤器不区分大小写

我有一本在 Swift 3 中填充 Pickerview 的字典。

var facilityDict:       [Int: [String: String]] = [:]

17: ["id": "199", "facilitycode": "036", "location_name": "中心点 医务室"],
41:[“id”:“223”,“设施代码”:“162”, "location_name": "黑岭医疗中心"],
14:[“id”:“196”, "facilitycode": "023", "location_name": "Spinnerpark"],
20:[“身份证”: "202", "facilitycode": "048", "location_name": "教育剧院"],
30:[“id”:“212”,“设施代码”:“090”,“location_name”:“合作伙伴 医务室"],
49:[“id”:“231”,“设施代码”:“223”, "location_name": "GreenBay 行政办公室"]

字典很长。我有一个Textbox,它在数据更改时触发,我用它来创建一个搜索变量。如果有人输入“ar”,我想过滤字典中包含字符“ar”的所有内容,以便我可以使用原始大字典列表中更小的子部分重置选取器列表。

过滤器 let filteredDictionaries = facilityDict.filter{$0.value.contains(where: {$0.value.contains("ar")})}.map{$0.value} 似乎可以很好地过滤字典,但是我需要搜索不区分大小写。我可以设置哪些选项来将过滤器显示更改为不区分大小写?

【问题讨论】:

  • 知道了。所以在这个例子中它是let filteredDict = self.sharedDataVal.departmentDict.filter{$0.value.contains(where: {($0.value.range(of: srchval, options: .caseInsensitive) != nil)})}.map{$0.value}

标签: ios swift3 xcode8


【解决方案1】:

包含方法它与range(of: "String") != nil 相同,没有任何选项。您只需要使用 String != nil 的范围和不区分大小写的选项:

extension String {
    func contains(_ string: String, options: CompareOptions) -> Bool {
        return range(of: string, options: options) != nil
    }
}

现在你可以这样做了:

"whatever".contains("ER", options: .caseInsensitive)

如果您需要从字典数组创建字典,则需要使用 forEach 遍历结果并从中重建字典:


let facilityDict: [Int: [String: String]] = [
    17: ["id": "199", "facilitycode": "036", "location_name": "Centerpoint Medical Offices"],
    41: ["id": "223", "facilitycode": "162", "location_name": "Dark Ridge Medical Center"],
    14: ["id": "196", "facilitycode": "023", "location_name": "Spinnerpark"],
    20: ["id": "202", "facilitycode": "048", "location_name": "Educational Theater"],
    30: ["id": "212", "facilitycode": "090", "location_name": "Partner Medical Offices"],
    49: ["id": "231", "facilitycode": "223", "location_name": "GreenBay Administrative Offices"]]

var filtered: [Int: [String: String]] =  [:]

facilityDict.filter{$0.value.contains{$0.value.contains("AR", options: .caseInsensitive)}}.forEach{filtered[$0.key] = $0.value}

print(filtered)  // [30: ["id": "212", "facilitycode": "090", "location_name": "Partner Medical Offices"], 41: ["id": "223", "facilitycode": "162", "location_name": "Dark Ridge Medical Center"], 14: ["id": "196", "facilitycode": "023", "location_name": "Spinnerpark"]]

【讨论】:

  • Leo,过滤器效果很好。但是结果是 [[String: String]]。我需要将结果返回到 [Int: [String: String]]。有什么建议吗?
  • 我在 .caseInsensitive 上收到“单元格中的额外参数'选项'”错误。我还注意到包含将匹配上面示例中的任何“AR”。如果我需要它来匹配诸如“AR 医疗中心”条目而不匹配“Spinnerpark”条目之类的明确内容怎么办?感谢协议提示!!!新手。
  • Leo,我还有一个额外的担忧,即我在稍微不同的数据上使用此过滤器,并且过滤器仅匹配正确的数据我得到重复值。我应该将其作为一个不同的问题打开吗?
猜你喜欢
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
相关资源
最近更新 更多