【发布时间】:2018-08-01 04:05:59
【问题描述】:
var sections = [[NoteItem]]()
var section = [NoteItem]()
sections.append(section)
someOtherArray.forEach{n in
section.append(n)
}
debugPrint("\(section.count)") // prints 75 which is the length of someOtherArray
debugPrint("\(sections[0].count)") // prints 0! Why??
最后的输出是我无法理解的。在 C#、Java 和我使用过的许多其他语言中,它与第二个(即 75)具有相同的输出,因为变量 section 和 sections 的第一个元素 sections[0] 只是同一个对象。
在 Swift 中,情况似乎并非如此。事实上,如果我这样做:
var sections = [[NoteItem]]()
var section = [NoteItem]()
someOtherArray.forEach{n in
section.append(n)
}
sections.append(section) // appending here after populating 'section'
debugPrint("\(section.count)") // prints 75 which is the length of someOtherArray
debugPrint("\(sections[0].count)") // prints 75 as expected!
我会得到预期的输出。
谁能解释一下?谢谢。
【问题讨论】: