2

I am working to implement search functionality for UITableView. Table may contain lot of rows so searching technique needs to be efficient. If code is compatible with Swift5 then it would be great.

I need a way where I can get list of items matching in array.

For ex: I have an array with these values "One", "Two", "Three", "Four", "Five"

If I search "o" then it should return "One", "Two", "Four" as array output

So I can fill UITableView with these new elements.

2
  • show your tried code, use UISearchbar Commented Nov 28, 2019 at 12:26
  • Show some code, it is hard to do anything without a codebase. Commented Nov 28, 2019 at 12:27

3 Answers 3

4

You can go this way it will return result array, that's such a efficient way for searching. the code is like below:

Code:

    let filtereddata = searchText.isEmpty ? yourArray : yourArray.filter({(dataString: String) -> Bool in
        // If dataItem matches the searchText, return true to include it
        return dataString.range(of: searchText, options: .caseInsensitive) != nil
    }) //searchText is your "o"(Search text)

    print(filtereddata,"results")

i hope it will help you,Thanks.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for quick response. I have NSMutableArray, Can you make this to work with that ?
if you have NSMutableArray you can go with developer.apple.com/documentation/foundation/nsmutablearray/… this method and filter your array
2

you can also go with simple way like this its easy to understand for beginners ..:)

var str = ["One","Two","Three","Four"]
var sortedstr = [String]()
for i in 0...str.count-1{
    if str[i].contains("o") || str[i].contains("O"){
        sortedstr.append(str[i])

    }
}

1 Comment

Hey Shivam, welcome to the site. Don't write code like this in Swift. It looks like Java, and it has a bunch of pitfalls. For one, this crashes when str is empty, because 0...str.count - 1 will evaluate to 0...-1, which will crash.
1

Using predicates is the best approach.

Here is a very useful link:

https://www.infragistics.com/community/blogs/b/stevez/posts/ios-objective-c-filtering-a-nsarray-using-nspredicate

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.