I lowercased the grocery item and searched for the singular version of the beans to account for other forms of spelling i.e. (‘Beans’, ‘beans’, ‘Bean’, ‘bean’, ‘BEAN’, etc). I also chose contains instead of the recommended hasSuffix in order to find all instances of the word. In long string’s this will be slower, but for this use case it’s negligible and a more forgiving search.
func siftBeans(fromGroceryList groceries: [String]) -> (beans: [String], otherGroceries: [String]) {
var beans = [String]()
var otherGroceries = [String]()
for item in groceries {
if item.lowercased().contains("bean") {
beans.append(item)
} else {
otherGroceries.append(item)
}
}
return (beans, otherGroceries)
}
The problem with using contains is that it will also match things like “bean salad” or “bean soup”. If you want to exclude those kinds of entries while still matching both bean and beans, you’d need to do two checks using hasSuffix.
Though I’m a bit curious why anyone would want to buy one single bean…
Here’s what I have so far for the silver challenge. I haven’t looked at your solution yet because I don’t want to just copy it. Any help with mine would be greatly appreciated.
//Silver Challenge
import Cocoa
func siftBeans(fromGroceryList list: [String], hasSuffix: Bool) -> (beans: [String], otherGroceries: String {
var beans = String
var otherGroceries = String
for item in list {
if item.hasSuffix(“beans”) {
beans.append(item)
} else {
otherGroceries.append(item)
}
}
return (beans, otherGroceries)
}
let result = siftBeans(fromGroceryList: [“green beans”, “pinto beans”, “black beans”, “apples”, “milk”])
let groceryList = siftBeans(result)
print(“The items with a beans suffix are (groceryList.beans); the other grocery list items are: (groceryList.otherGroceries)”)
***for my code above ^
var beans = String is supposed to have brackets around String and empty parentheses (to assign it to an empty array)…the same goes for otherGroceries.
let list = ["green beans", "milk", "black beans", "pinto beans", "apples"]
var beans: [String] = []
var otherGroceries: [String] = []
for item in list {
if item.hasSuffix("beans") {
beans.append(item)
} else {
otherGroceries.append(item)
}
}
return (beans, otherGroceries)
}
/* having trouble printing the results now…
let groceryList = [“green beans”, “milk”, “black beans”, “pinto beans”, “apples”]
siftBeans(fromGroceryList: list)
print(“The beans list is: (groceryList.beans); the other groceries are: (groceryList.otherGroceries)”)
*/
/* this prints but looks weird…
siftBeans(fromGroceryList: [“green beans”, “milk”, “black beans”, “pinto beans”, “apples”])
print(siftBeans(fromGroceryList: [“green beans”, “milk”, “black beans”, “pinto beans”,“apples”]))
*/