Home > Software engineering >  how to filter dictionary based on their value character swift
how to filter dictionary based on their value character swift

Time:01-06

i have to filter dictionary containing my text inside of textfield //my code

var arrayData = [["Name":"Sahil"],["Name":"Raman"],["Name":"ashish"],["Name":"Vishnu"],["Name":"Deep"],["Name":"sahil"],["Name":"Swift"]]
//my result should be  like this
[["Name":"Sahil"],["Name":"ashish"],["Name":"Vishnu"],["Name":"Swift"]]

CodePudding user response:

This should work:

var arrayDataFiltered = arrayData.filter { $0["Name"]?.lowercased().contains("s") ?? false }

Here is the documentation for filtering: https://developer.apple.com/documentation/swift/sequence/3018365-filter

CodePudding user response:

It was unclear, you explained it later in comments, but you want to keep the values for key "Name" which contains an "s" case insensitive.

Let's add a couple of additional values to show why your previous attempts failed:

var arrayData = [["Name":"Sahil"],
                 ["Name":"Raman"],
                 ["Name":"ashish"],
                 ["Name":"Vishnu"],
                 ["Name":"Deep"],
                 ["Name":"sahil"],
                 ["Name":"Swift"],
                 ["Name":"s"],
                 ["Name":"S"]]

And simplify:

let searchText = "s" // textField.text ?? ""

You attempted:

let filteredArray1 = arrayData.filter { $0["Name"] == searchText }
print(filteredArray1)

Output:

$> [["Name": "s"]]

So, you get only when value is exactly equals to "s", that's normal, you are using ==

You then attempted:

let filteredArray2 = arrayData.filter { $0["Name"]!.contains(searchText) }
print(filteredArray2)

Output:

$>[["Name": "ashish"], ["Name": "Vishnu"], ["Name": "sahil"], ["Name": "s"]]

So, you are getting anyvalues when it has a "s" inside it. It's almost that, but you aren't getting when it has an uppercase "S". To do that, you can use range(of:options:searchRange:local:) with .caseInsensitive optiono. If the result isn't nil, it means it has been found.

So you can use:

let filteredArray3 = arrayData.filter { $0["Name"]?.range(of: "s", options: .caseInsensitive) != nil }
print(filteredArray3)

Output:

$>[["Name": "Sahil"], ["Name": "ashish"], ["Name": "Vishnu"], ["Name": "sahil"], ["Name": "Swift"], ["Name": "s"], ["Name": "S"]]
  •  Tags:  
  • Related