我有一个方法,它应该返回一组字符串。下面是一个方法描述:
- 返回:包含指定字符串的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
}
}
如果你想实现这一点,你需要迭代你的resultArray
和producer
和product
保存到另一个数组。在每次迭代中,您需要检查数组allready是否包含产品名称本身或allready修改后的版本。
一个可能的实现是这样的:
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")
结果:
["name13", "producer12 name1", "name10", "name19", "producer11 name1",name17", "name14", "name18", "producer1 name1", "name16"]