I have to filter a dictionary containing my text inside of a textfield.
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"]]
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"]]