如何快速过滤包含包含属性的数组

时间:2021-01-09 06:08:16

标签: arrays swift filter contains

(注释行)有效,但它仅过滤以 im writing 一词开头的产品

如果过滤名称包含我在搜索栏中写的任何内容,我会尝试做什么

while 方法是我试图解决它但根本不起作用

我尝试使用该函数的 contains 方法,但它向我展示了大量结果,它复制了结果

// 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()

3 个答案:

答案 0 :(得分:1)

您可以尝试使用 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)
    }
}

答案 1 :(得分:1)

照你说的写:

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

答案 2 :(得分:0)

非常感谢所有回答这个问题的人

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