Parth Adroja
Parth Adroja

Reputation: 13514

How to filter string array from first index rather then containing char?

I have an array of countries. I need to search and update array with searched text but starting with initial char match not anywhere in the string.

For eg: If I search in it should return India, Indonesia... not ChINa...

I have created bleow method which looks into whole string rather then initial char.

Also, I don't have any range in this function so how can I get range from string?

func searchCountry(for string: String) {
        if !string.isEmpty {
            let filtered = countries?.filter {
                $0.name?.range(of: string,
                               options: .caseInsensitive) != nil
            }
            guard let filteredCountries = filtered else { return }
        }
    }

Upvotes: 0

Views: 83

Answers (2)

Niilesh R Patel
Niilesh R Patel

Reputation: 707

You can also use this for appropriate output

func searchCountry(for string: String?) {
        if let searchText = string {
            let filter = countries.filter({ $0.lowercased().hasPrefix(searchText.lowercased()) })
            print(filter)
        }
    }

Upvotes: 3

Muhammad Zohaib Ehsan
Muhammad Zohaib Ehsan

Reputation: 931

 $0.name?.range(of: string,options: [.anchored, .caseInsensitive]) != nil

Use anchored to search the initials. It starts from the start.

Upvotes: 2

Related Questions