在Swift数组或字典中搜索和编辑值

46scxncf  于 2022-11-21  发布在  Swift
关注(0)|答案(1)|浏览(112)

我有一个方法,它应该返回一组字符串。下面是一个方法描述:

  • 返回:包含指定字符串的10个产品名称。如果有多个产品具有相同的名称,则以"<producer> - <product>“格式将生产商的名称添加到产品名称中,否则仅返回"<product>"

不知道如何检查数组中是否有重复的名称,然后根据需要编辑它们
目前为止我得到的信息是:

struct Product {
    let id: String; // unique identifier
    let name: String;
    let producer: String;
}

protocol Shop {

    func addNewProduct(product: Product) -> Bool

    func deleteProduct(id: String) -> Bool
    
    func listProductsByName(searchString: String) -> Set<String>
    
    func listProductsByProducer(searchString: String) -> [String]
}

class ShopImpl: Shop {
    
    private var goodsInTheShopDictionary: [String: Product] = [:]
        
    func addNewProduct(product: Product) -> Bool {
        let result = goodsInTheShopDictionary[product.id] == nil
        if result {
            goodsInTheShopDictionary[product.id] = product
        }
        return result
    }
    
    func deleteProduct(id: String) -> Bool {
        let result = goodsInTheShopDictionary[id] != nil
        if result {
            goodsInTheShopDictionary.removeValue(forKey: id)
        }
        return result
    }

    
    func listProductsByName(searchString: String) -> Set<String> {
        var result = Set<String>()
    
        let searchedItems = goodsInTheShopDictionary.filter{ $0.value.name.contains(searchString) }
        let resultArray = searchedItems.map{ $0.value }
        
        
        
        result = Set(searchedItems.map{ $0.value.name })
        if result.count > 10 {
            result.removeFirst()
        }

        return result
        
    }
    

}
goucqfw6

goucqfw61#

如果你想达到这个目的,你需要迭代resultArray,并将producerproduct保存到另一个数组中。在每次迭代中,你需要检查数组是否已经包含了产品名称本身或已经修改过的版本。
可能的实现如下所示:

var result = [(producer: String, product: String)]()
// iterate over the first 10 results
for item in resultArray.prefix(10){
    if let index = result.firstIndex(where: { _ , product in
        product == item.name
    }){
        // the result array allready contains the exact product name
        // so we need to convert the name allready in the list
        let oldProduct = (producer: result[index].producer, product: "\(result[index].producer) \(result[index].product)")
        result[index] = oldProduct
        // add the new one
        result.append((producer: item.producer, product: "\(item.producer) \(item.name)"))
    }
    else if !result.filter({ $0.product.components(separatedBy: " ").contains(item.name)}).isEmpty {
        // if the result array allready contains a modified version of the name
        result.append((producer: item.producer, product: "\(item.producer) \(item.name)"))
    } else{
        // if the result array does not contain the product yet
        result.append((producer: item.producer, product: "\(item.name)"))
    }
}

let productNames = result.map{ $0.product}

请注意:由于您使用[String: Product](一个未排序的字典)来保存值,因此每次搜索时都会产生不同的结果(如果resultArray集合大于10)。
使用searchString = name1进行测试:

var goodsInTheShopDictionary: [String: Product] = Dictionary(uniqueKeysWithValues: (0...20).map { index in
    ("\(index)",Product(id: "", name: "name\(index)", producer: "producer\(index)"))
})

goodsInTheShopDictionary["100"] = Product(id: "11", name: "name1", producer: "producer11")
goodsInTheShopDictionary["101"] = Product(id: "12", name: "name1", producer: "producer12")

结果:
[“名称13,““生成器12名称1,““名称10,““名称19,““生成器11名称1,““名称17,”“名称14,““名称18,”“生成器1名称1,““名称16”]

相关问题