apple swift - 从变量引用数组

时间:2016-07-14 18:16:43

标签: arrays swift

swift的新手,一个人为的例子。 我有一系列菜单类别,而这些菜单类别又包含菜单项 我想循环遍历类别,然后读取子项数组的元素。不知道将元素引用为数组的语法

第10行的错误,第18栏:类型'字符串'不符合协议'序列'    (项目)提供{

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 个答案:

答案 0 :(得分:6)

menuOffering是一个String数组,因为您已在引号中定义它。在这种情况下drinksbreakfastEntree。所以你试图迭代一个字符串并得到错误。而是将数组menuOffering定义如下:

var menuOffering = [drinks , breakfastEntree] // without quotes

现在它将是数组。 你修改过的代码应该是:

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

}

答案 1 :(得分:1)

menuOffering是一个集合数组。如果没有引号,变量名称现在可以访问集合包含的值,并且可以在下面看到的嵌套表单中迭代它们。

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

如果您没有尝试在字符串中包含变量名,您也可以打印上面的变量,如下所示:

print("string: \(variableName)")

确保不要在“print”和括号之间加一个空格。