Navneet Kaur
Navneet Kaur

Reputation: 359

How to filter and show data in table view swift 5?

I'am trying to filter the array and add the filtered values in new array and show them in table view..

var names = [String]()
names = ["Name","Student","Roll No"]

    func textFieldDidChangeSelection(_ textField: UITextField) {
            print("start changes")
            
            if names.contains(where: {$0 == txtSearch.text})
            {
                tblRestaurantData.reloadData()
            } else {
               //item could not be found
            }

i've written the above code but i am confused how to get and display the filtered values in tableview ?

Upvotes: 1

Views: 1114

Answers (2)

Chaman Sharma
Chaman Sharma

Reputation: 636

Use this

func textFieldDidChangeSelection(_ textField: UITextField) {
   let resultArray = names.filter({ (value) -> Bool in
        if value.contains(txtSearch.text) {
            return true
        } else {
            return false
        }
    })
}

Upvotes: 1

esemusa
esemusa

Reputation: 161

try something like this:

func textFieldDidChangeSelection(_ textField: UITextField) {
    if !names.contains(textField.text ?? "") {
        names.append(textField.text ?? "")
        tblRestaurantData.reloadData()
    }
}

Upvotes: 1

Related Questions