Functions: Silver Challenge - my solution


#1
//Silver Challenge
func siftBeans(fromGroceryList stuff: [String]) -> (beans: [String], otherGroceries: [String])  {
    var i: Int = 0
    var beans = [String]()
    var otherGroceries = [String]()
    while i < stuff.count {
        let thisItem = stuff[i]
        if thisItem.contains("beans") || thisItem.contains("Beans") {
            beans.append(thisItem)
        } else {
            otherGroceries.append(thisItem)
        }
        i += 1
    }
    return(beans, otherGroceries)
}
// Call the function sending the grocery list
let results = siftBeans(fromGroceryList: ["green beans", "milk", "black beans", "pinto beans", "apples", "ugly Beans"])

//Print the returns
print("The beans in the list are:  \(results.beans).")
print("The other groceries in the list are: \(results.otherGroceries).")

#2

// Silver Challenge: I made this work, but is there a cleaner way to write this? Also I do not understand the need for the optional call out and force unwrap in this part of my code… (item?.contains(“beans”))! {

let GroceryList = [“green beans”,“beans”, “milk”, “black beans”, “pinto beans”, “apples”]
func siftBeans(fromGroceryList list: [String?]) -> (beans: [String?], otherGroceries: [String?]) {
var beans = String?
var otherGroceries = String?
if list.count > 0 {
for i in 0…(list.count - 1) {
let item = list[i]
if (item?.contains(“beans”))! {
beans.append(item)
} else {
otherGroceries.append(item)
}
}
}
print(beans, otherGroceries)
return (beans, otherGroceries)
}

siftBeans(fromGroceryList: GroceryList)