Filter Dictionary with a case insensitive search

前端 未结 1 565
生来不讨喜
生来不讨喜 2020-12-22 04:12

This is a follow-up question on How to Filter a Dictionary only I need the filter to be case-insensitive

I have a dictionary that populates a Picker

相关标签:
1条回答
  • 2020-12-22 04:50

    Contains method it is the same as range(of: "String") != nil without any options. All you need is to use range of String != nil with caseInsensitive options:

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

    Now you can do:

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

    If you need to create a dictionary from your array of dictionaries, you would need to use forEach to iterate through the result and rebuild your dictionary from it:


    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"]]
    
    0 讨论(0)
提交回复
热议问题