【发布时间】:2017-01-27 00:45:19
【问题描述】:
为什么这段代码不起作用? 我有一个名为 answers 的数组,它是一个包含字符串数组集合的数组。 我在这里尝试做的是访问我的“答案”数组中的单个数组,该数组由答案 [count] 表示。然后使用通过下标访问该子数组中的每个字符串值。
错误消息:“下标”不可用。不能用 Int 为 String 下标。
func showQuestionAndAnswer( b0: RoundedButton, b1: RoundedButton, b2: RoundedButton, b3: RoundedButton, count: Int) -> Void {
// When a question is answered, count += 1, such that my questionsLabel will show next question in questions array, and buttons will show possible answers to choose from.
// Set label to proper question.
questionLabel.text = questions[count]
// answers is of type [ [String], [String]...]
for subArray in answers[count] {
// answers[count] tells me which array of answers I should look into.
// subArray should be a single array with string values.
// Each sub array has a unique number of string values. Each value should be placed as title for resective button.
switch subArray.count {
case 4 :
b0.titleLabel?.text
= subArray[0]
b1.titleLabel?.text = subArray[1]
b2.titleLabel?.text = subArray[2]
b3.titleLabel?.text = subArray[3]
break
case 3 :
b0.titleLabel?.text = subArray[0]
b1.titleLabel?.text = subArray[1]
b2.titleLabel.text = subArray[2]
break
case 2 :
b0.titleLabel?.text = subArray[0]
b1.titleLabel?.text = subArray[1]
break
default:
b0.titleLabel?.text = "No Answers"
}
}
}
【问题讨论】:
-
你不需要(也不应该)在 Swift 中显式地输入
break。除非明确告知fallthrough,否则案件总是会中断。 -
那么
questions的声明呢? -
如果
answers是[[String]],那么answers[count]是[String],因此subArray是String,而不是数组。
标签: arrays string for-loop multidimensional-array swift3