【问题标题】:Swift array init : data[section][row]Swift 数组初始化:数据[节][行]
【发布时间】:2016-11-22 15:48:19
【问题描述】:

在 Swift 中,我将我的 var 定义为:

var data : [[[String : Any]]] = [[[:]]]

然后初始化它:

    for section in 0...1 {
        for row in 0...19 {
            let streamer = [
                "name" : "abcdef"
            ]
            data[section][row] = streamer
        }
    }

但是对于索引data[0][1],我得到fatal error: Index out of range.,但索引data[0][0] 没有错误。

有人知道我为什么会收到这个错误吗?

【问题讨论】:

  • 您正在使用原始的硬编码索引来尝试访问数组的元素。你预计会发生什么?
  • 你可以先检查data[section][row]是否存在(检查它是否等于nil)并且只有当它 nil时才给它赋值

标签: arrays swift dictionary swift3


【解决方案1】:

我看到了问题,出于某种原因,我认为 swift 在我通过下标访问它们时会自动插入一个部分和行,但似乎不是这样,所以我将我的 init 更改为:

       for sectionIndex in 0...1 {
            var section : [[String : Any]] = [[:]]
            for rowIndex in 0...19 {
                let streamer = [
                    "name" : "abcdef"
                ]
                section.insert(streamer, at: rowIndex)
            }
            data.insert(section, at: sectionIndex)
        }

【讨论】:

  • some reason 是:Swift Array 是值类型而不是引用类型。
  • @vadian 谢谢,我完全忘记了 swift 的数组是值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2020-09-21
  • 2018-08-11
相关资源
最近更新 更多