/**
The task is to implement the Shop protocol (you can do that in this file directly).
- No database or any other storage is required, just store data in memory
- No any smart search, use String method contains (case sensitive/insensitive - does not matter)
– Performance optimizations for listProductsByName and listProductsByProducer are optional
*/
struct Product {
let id: String; // unique identifier
let name: String;
let producer: String;
}
protocol Shop {
/**
Adds a new product object to the Shop.
- Parameter product: product to add to the Shop
- Returns: false if the product with same id already exists in the Shop, true – otherwise.
*/
func addNewProduct(product: Product) -> Bool
/**
Deletes the product with the specified id from the Shop.
- Returns: true if the product with same id existed in the Shop, false – otherwise.
*/
func deleteProduct(id: String) -> Bool
/**
- Returns: 10 product names containing the specified string.
If there are several products with the same name, producer's name is added to product's name in the format "<producer> - <product>",
otherwise returns simply "<product>".
*/
func listProductsByName(searchString: String) -> Set<String>
/**
- Returns: 10 product names whose producer contains the specified string,
result is ordered by producers.
*/
func listProductsByProducer(searchString: String) -> [String]
}
Проблема с реализацией протокола, не хватает знаний
не понимаю как реализовать вот эту часть: func listProductsByName(searchString: String) -> Set<String>
как отсортировать по вводимому тексту и в случае если похожих значений много вывести в формате <producer, name>
Сперва поиск
let searchResults = productsArray.filter { $0.name.contains(searchString) }.prefix(10)
Дальше поиск дубликатов
let crossReference = Dictionary(grouping: searchResults, by: \.name)
let duplicates = crossReference
.filter { $1.count > 1 }
И формирование вывода
var results = Array(Set(searchResults.map {.$0.name }))
results.append(contentsOf: duplicates.map { "\($0.producer) - \($0.name)" })
Как-то так наверное
Спасибо! Попробую!
Вообще если быть точным, у меня class ShopTml который поддерживает протокол Shop, все функция и сам протокол я прикрепил выше
А так же есть массив структуры [Product]
Задача функции func addNewProduct(product: Product) -> Bool
проверять есть ли такой id уже в массиве и возвращать true или false для этого я сделал так:
private func indexProduct(_ string: String) -> Int {
var int = 0
if let integer = Int(string) {
int = integer
}
return int
}
func addNewProduct(product: Product) -> Bool {
let id = indexProduct(product.id)
let index = id - 1
let shopID = indexProduct(shopProduct[index].id)
if id == shopID {
return false
} else {
shopProduct.append(product)
return true
}
}
аналогично с добавлением но только в другую сторону
func deleteProduct(id: String) -> Bool {
let id = indexProduct(id)
let index = id - 1
let shopID = indexProduct(shopProduct[index].id)
if id == shopID {
shopProduct.remove(at: index)
return true
} else {
return false
}
}
и 2 функции на поиск
func listProductsByName(searchString: String) -> Set {
}
func listProductsByProducer(searchString: String) -> [String] {
var nameProducer: [String] = []
for product in shopProduct {
let name = product.name
if name.lowercased().contains(searchString.lowercased()) {
nameProducer.append(product.producer)
}
}
return nameProducer
}
и вот в этом контексте у меня не получается реализовать функцию listProductsByName(searchString: String) -> Set
которая должна: Возвращать 10 названий продуктов, содержащих указанную строку. При наличии нескольких товаров с одинаковым названием к названию товара добавляется имя производителя в формате “<производитель> - <продукт>”, в противном случае возвращается просто “<продукт>”.
вот если это как поменяет то решение которое прислали Вы, то если не трудно прошу прислать, а то весь день мозг кипит догнать не могу:cold_face:
Я уже ничего не понимаю.
Вы сказали что не понимаете как реализовать метод listProductsByName.
Я вам написал примерный код (я не проверял его).
Далее вы пишете “спасибо и попробуете” и в конце просите прислать код???