Swift数组/字典搜索编辑:重复商品名格式化实现问题
实现Shop协议的listProductsByName方法
需求说明:
- 返回包含指定搜索字符串的最多10个商品名集合
- 存在同名商品时,格式化为
<producer> - <product>;无同名则直接返回商品名
修正后的完整代码:
struct Product { let id: String // 唯一标识符 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> { // 1. 筛选出名称包含搜索字符串的所有商品 let filteredProducts = goodsInTheShopDictionary.values.filter { $0.name.contains(searchString) } // 2. 统计每个商品名出现的次数,判断是否有同名 var nameCount: [String: Int] = [:] filteredProducts.forEach { product in nameCount[product.name, default: 0] += 1 } // 3. 格式化每个商品的显示名称 let formattedNames = filteredProducts.map { product -> String in if nameCount[product.name] ?? 0 > 1 { return "\(product.producer) - \(product.name)" } else { return product.name } } // 4. 取最多10个结果,转为Set返回 let limitedResults = Array(formattedNames.prefix(10)) return Set(limitedResults) } }
关键逻辑说明:
- 筛选商品:通过
filter方法从字典的values中筛选出名称包含搜索字符串的Product实例 - 统计名称频率:用字典
nameCount记录每个商品名出现的次数,以此判断是否存在同名商品 - 格式化名称:遍历筛选后的商品,若该名称出现多次,则拼接生产者和商品名;否则直接返回商品名
- 限制返回数量:用
prefix(10)获取前10个格式化后的结果,再转为Set(符合方法返回类型要求)
内容的提问来源于stack exchange,提问作者Mark Pushkar
相关产品推荐
相关产品推荐

