【问题标题】:How to work with 2d Array in swift 3?如何在 swift 3 中使用 2d 数组?
【发布时间】: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],因此subArrayString,而不是数组。

标签: arrays string for-loop multidimensional-array swift3


【解决方案1】:

答案必须是 [[String]] 才能调用 .count

你也需要打电话

for subArray in answers{
}

【讨论】:

  • @Alexander:感谢关于休息的提示。答案和问题的声明不包含在这个 sn-p 中。问题是,如果我将 subArray 打印到控制台,它将提供数组中的所有字符串值。我只是不能通过下标单独访问值。
  • 如果你使用上面提到的for循环会发生什么?
  • 哈米什是对的。我只是将所需的数组分配给一个常量。我让事情变得比他们必须的更困难。示例:让 subArray = answers[count]... 大声笑。感谢各位的帮助。
【解决方案2】:

这里正如你所说的答案是字符串数组的数组,这意味着它就像这样var answers:[[string]]

所以你可以像下面这样迭代

for subArray in answers {
  //here subArray would of type [String]
  switch subArray.count{
    //Your code
  }
}

PS。 Alexander 对 break 语句的看法是正确的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 2017-07-30
    • 1970-01-01
    • 2020-09-20
    相关资源
    最近更新 更多