Reputation: 11
In the following code, how do I get the return value to be addressable by name? Currently the return value has to be accessed with result.0 and result.1 I would like to be able to access them with result.beans and result.other
var groceryList = ["Baked Beans", "Green Beans", "Runner Beans", "Carrots", "Potatoes"]
func siftBeans(groceryList fromGroceryList: [String]) -> ([String],[String]){
var newLists: (beans: [String], otherGroceries:[String]) = ([],[])
for groceryItem in fromGroceryList {
if groceryItem.hasSuffix("Beans") {
newLists.beans.append(groceryItem)
} else {
newLists.otherGroceries.append(groceryItem)
}
}
return (beans: newLists.beans, other: newLists.otherGroceries)
}
let result = siftBeans(groceryList: groceryList)
result.0
result.1
Upvotes: 1
Views: 255
Reputation: 271040
You need to specify the names in the return type:
func siftBeans(groceryList fromGroceryList: [String])
-> (beans: [String], other: [String]) {
// ^^^^^ ^^^^^
// ...
}
To make your method shorter, you can make a type alias for this tuple type:
typealias SiftedBeans = (beans: [String], other: [String])
func siftBeans(groceryList fromGroceryList: [String]) -> SiftedBeans {
Upvotes: 1