【问题标题】:Why does Swift Array behave differently from Lists of other languages?为什么 Swift Array 的行为与其他语言的 List 不同?
【发布时间】: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)具有相同的输出,因为变量 sectionsections 的第一个元素 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!

我会得到预期的输出。

谁能解释一下?谢谢。

【问题讨论】:

    标签: arrays swift


    【解决方案1】:

    Array、Dictionary、String 和许多其他类型都是基于 Swift 的 Value。

    所以“它们是同一个对象”是没有意义的,因为当你将它添加到部分时,你只是在复制部分值。

    【讨论】:

    • 我不知道 Swift 中的数组是值类型(与其他语言不同)。所以当 'section' 添加到 'sections' 时,'section' 的内容会被复制到另一个数组中。谢谢。
    • 不仅仅是 Swift,在函数式语言或不可变语言中,几乎所有类型都使用值语义。我建议阅读(COW-CopyOnWrite)。
    猜你喜欢
    • 2021-09-15
    • 2020-10-23
    • 2017-04-03
    • 2014-08-12
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多