Samuel Montoya
Samuel Montoya

Reputation: 41

how to filter an array with contains property in swift

the (commented lines) works but it only filters the products that initiates with the word im writing

what im trying to do if filtering if the name contains whatever im writing in the search bar

the while method is how im trying to solve it but is not working at all

I've tried using the contains method of the function but it shows me tons of results it duplicates the results

// productosBuscados=productos.filter{$0.Descripcion.lowercased().prefix(searchText.count)==searchText.lowercased()}//

        var contador=0
        while contador<productos.count-1{
            if(productos[contador].Descripcion.contains(buscador.text!)){
                productosBuscados.append(productos[contador])
                print(productos[contador].Descripcion+" este producto concuerda")
            }
            contador+=1
        }
        buscando = true
        tabla.reloadData()

Upvotes: 1

Views: 2632

Answers (3)

Samuel Montoya
Samuel Montoya

Reputation: 41

thanks a lot for all that replied the solution was this one

productosBuscados = buscador.text!.isEmpty ? productos : productos.filter {
            $0.Descripcion.lowercased().contains(buscador.text!.lowercased())
        }

Upvotes: 1

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119128

Just write it as you say it:

let result = products.filter { $0.Descripcion.contains("whatever im writing in the search bar") }

Upvotes: 1

you can try using searchBar for solving this kind of problems. Here is an example of how you use the searchBar;

import UIKit

class ViewController: UIViewController,UISearchBarDelegate {

    //MARK: - IBOutlets
    @IBOutlet weak var serachBar: UISearchBar!
    
    //MARK: - Variables
    var rawData:[String] = ["Taha","Yasin","Samet","Sumeyye","Seda","Esra","Muhammet","Zeynep","Ishak","Fatma"]
    var filteredData:[String]!

    override func viewDidLoad() {

        super.viewDidLoad()
        
        serachBar.delegate = self
        filteredData = rawData
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        filteredData = searchText.isEmpty ? rawData : rawData.filter {
            $0.contains(searchText)
        }
        //It prints the data from the filtered array contains the text that you searched from the search bar and the print method will be called after every caracter that you add the search bar.
        print(filteredData)
    }
}

Upvotes: 1

Related Questions