【发布时间】:2022-11-20 18:48:41
【问题描述】:
我有一个应该返回一组字符串的方法。下面是方法说明:
- 返回: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
}
}
【问题讨论】:
-
不是将 value.name 映射到 resultArray 上的 Set 循环中,而是检查每个名称是否在结果中(可以是数组或集合),然后添加它或将其与生产者名称一起添加。然后对该结果使用
prefix(10)以获取前 10 个或在找到 10 个项目后中断循环。
标签: arrays swift dictionary