首页 > 解决方案 > 在uitableview中过滤多维数组 - swift

问题描述

这是我的模型

class BusinessProfile: NSObject {
    var title: String?
    var website: String?
    var associatedOrganization: String?
    var companyName: String?
    
    var productList: [BusinessProfileProduct]?
}

class BusinessProfileProduct: NSObject{    
    var productName: Double?
    var modelNumber: String?
    var hsCode: String?
}

这是我在视图控制器中的数组变量。

var businessProfileArray = [BusinessProfile]()
var tempBusinessProfileArray = [BusinessProfile]()

我已经根据 companyName 过滤了 businessProfileArray,如下所示:

tempBusinessProfileArray = businessProfileArray.filter({ (BusinessProfile) -> Bool in
            return (BusinessProfile.companyName!.lowercased().contains(searchText.lowercased()))
        })

但是我无法从 BusinessProfileProduct 的嵌套数组中根据 productName 或 hsCode 过滤 businessProfileArray。

注意:businessProfileArray 包含 businessProfileProduct 数组

任何人的帮助?提前致谢。

标签: swiftuitableviewmultidimensional-arrayfilter

解决方案


你可以做类似的事情

func filterArr(searchText:String) -> [BusinessProfile] {
    var filteredArr = [BusinessProfile]()
    for profile in businessProfileArray {
        var isMatched = false
        
        if let matchedProduct = profile.productList.filter ({$0.companyName.lowercased().contains(searchText.lowercased())}).first {
            isMatched = true
            print(matchedProduct.companyName)
        }
        
        if isMatched {
            filteredArr.append(profile)
        }
        
    }
    
    return filteredArr
}

这将返回 searchText 与产品的 companyName 匹配的所有配置文件,但是它不会删除与 searchText 不匹配的额外产品


推荐阅读