Reputation: 39
newbie to swift, a contrived example. I have an array of menu categories, which in turn have menu items I want to loop through the categories and then read the elements of the sub-array of items. Don't know the syntax to reference the element as an array
ERROR at line 10, col 18: type 'String' does not conform to protocol 'Sequence' for (item) in offering {
var menuOffering = ["drinks" , "breakfastEntree"]
var drinks: Set = ["water","milk","coffee","tea","diet coke"]
var breakfastEntree: Set = ["eggs", "bacon", "sausage","pancakes"]
for ( offering) in menuOffering {
print ("\(offering)")
for (item) in offering { ERROR
print ("\(item)")
}
}
Upvotes: 2
Views: 71
Reputation: 422
menuOffering is an Array of Sets. Without the quotes, the variable names now access the sets' contained values and they can be iterated over in the nested form you'll see below.
let drinks: Set = ["water", "milk", "coffee", "tea", "diet coke"]
let breakfastEntree: Set = ["eggs", "bacon", "sausage", "pancakes"]
let menuOffering = [drinks, breakfastEntree]
for offering in menuOffering {
for item in offering {
print(item)
}
}
You can also print variables out I did above if you are not trying to include a variable name in a String as below:
print("string: \(variableName)")
Make sure not to include a space between "print" and the parentheses.
Upvotes: 1
Reputation: 1378
menuOffering
is a String
array because you have defined it in quotes. In this case drinks
and breakfastEntree
. So you are trying to iterate over a String and getting error. Instead, define your array menuOffering
as follow:
var menuOffering = [drinks , breakfastEntree] // without quotes
Now it will be array of sets. You modified code should be :
var drinks: Set = ["water","milk","coffee","tea","diet coke"]
var breakfastEntree: Set = ["eggs", "bacon", "sausage","pancakes"]
var menuOffering = [drinks , breakfastEntree]
for ( offering) in menuOffering {
for (item) in offering {
print ("\(item)")
}
}
Upvotes: 6