如何在swift中过滤包含属性的数组

Posted

技术标签:

【中文标题】如何在swift中过滤包含属性的数组【英文标题】:how to filter an array with contains property in swift 【发布时间】:2021-04-14 19:16:51 【问题描述】:

(注释行)有效,但它只过滤以单词 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()

【问题讨论】:

如果我理解正确,这里是the answer。如果不是,请详细说明问题并添加一些产品示例进行演示。 嘿,你找到答案了吗? 【参考方案1】:

您可以尝试使用 searchBar 来解决此类问题。下面是一个如何使用 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)
    

【讨论】:

不错的方法 kanka :) 实际上这就是我正在尝试的,但它似乎不起作用【参考方案2】:

照你说的写:

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

【讨论】:

这其实已经是问题的一部分了 和那个差不多,不一样@JoakimDanielson 是的,不完全相同,但这如何解决 OP 在使用 contains 时遇到的问题? OP 在问题中使用了“计数”和“前缀”,这是意料之中的。此代码是标题要求的正确用法。它也不会返回重复的结果。如果他再次遇到极端情况错误,该操作可以提供一些样本:) 请再次阅读问题。这是我们正在讨论的 while 循环中的代码,但我同意重复有点奇怪【参考方案3】:

非常感谢所有回复的解决方案就是这个

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

【讨论】:

以上是关于如何在swift中过滤包含属性的数组的主要内容,如果未能解决你的问题,请参考以下文章

Swift:获取由某个属性过滤的对象数组的索引

如何在 Swift 中过滤字符串数组

如何在swift 3中过滤UISearchBar中的数组模型

在 Swift 中过滤对象数组并求和它们的属性

如何在 Swift 中设置属性本身可变的属性值

用于多重过滤 Swift 的布尔语句