0

I want to search a string in array and get all indexes at which string is present.

My Array consisting of json data coming from server is.

["Non Native", "Native", "Native & Non Native"]

The method I am using is

let indexArray = demand.indices.filter {
   demand[$0].localizedCaseInsensitiveContains("Native") 
}
                
print(indexArray)

But my problem is I get all of the three indexes. I just want only Native indexes (as in this case second index). (As much as I searched although it is part of other indexes too). Any help will be highly appreciated.

1
  • 2
    If you use localizedCaseInsensitiveContains, then sure, all three of three of them contain "Native". That is what "contain" means. Commented Jan 26, 2021 at 18:49

2 Answers 2

3

You are filtering contains, all items contain "Native", you have to filter is equal aka compare

let indexArray = demand.indices.filter { demand[$0].localizedCaseInsensitiveCompare("Native") == .orderedSame }           
print(indexArray)
Sign up to request clarification or add additional context in comments.

Comments

0

You are using the localizedCaseInsensitiveContains method, which returns everything that contains "Native" while being case-insensitive.

It sounds like your goal is to filter the array and return only values that are equal to "Native"


The previous Answer has a great solution for accomplishing this. However, here is a more simple one:

let indexArray = demand.indices.filter { demand[$0] == "Native" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.