我有一个方法,它应该返回一组字符串。下面是一个方法描述:
- 返回:包含指定字符串的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
}
}
1条答案
按热度按时间goucqfw61#
如果你想达到这个目的,你需要迭代
resultArray
,并将producer
和product
保存到另一个数组中。在每次迭代中,你需要检查数组是否已经包含了产品名称本身或已经修改过的版本。可能的实现如下所示:
请注意:由于您使用
[String: Product]
(一个未排序的字典)来保存值,因此每次搜索时都会产生不同的结果(如果resultArray
集合大于10)。使用
searchString = name1
进行测试:结果:
[“名称13,““生成器12名称1,““名称10,““名称19,““生成器11名称1,““名称17,”“名称14,““名称18,”“生成器1名称1,““名称16”]