2

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)")
    }

}
2
  • From your description, you probably don't want Sets here anyway. You probably just want arrays, so you can drop the : Set and let type inference do the work for you. Sets are unordered (so these could print out in any order), and are generally used when the collection could be very large and a common operation is "test wether X is a member of the set." For day-to-day use, you generally want Arrays (which is why you get them for free if you don't ask for : Set). To your actual question, see triple.s below. Commented Jul 14, 2016 at 18:44
  • thanks for the solutions.... tracking now Commented Jul 14, 2016 at 20:13

2 Answers 2

6

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)")
    }

}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.