[Swift] 数组恒等 === 的 bug?!

Posted 飘飘白云

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Swift] 数组恒等 === 的 bug?!相关的知识,希望对你有一定的参考价值。

Swift 中的数组是由结构体实现的:

struct Array<T> : MutableCollection, Sliceable 
    typealias Element = T
    var startIndex: Int  get 
    var endIndex: Int  get 
    subscript (index: Int) -> T
    func generate() -> IndexingGenerator<T[]>
    typealias SliceType = Slice<T>
    subscript (subRange: Range<Int>) -> Slice<T>
    init(_ buffer: ArrayBuffer<T>)

由上面的代码可以猜到,数组自身是不存放元素的,数组关联到一个存放元素的 buffer(元素存储区)。

而数组的恒等 === 在文档中是这么说的:

Check whether two arrays or subarrays share the same storage and elements by comparing them with the identity operators (=== and !==).

数组的恒等 === 判断即判断两个数组所关联的元素存储区是否相同。

但 XCode 6 Beta 测试下来,结果大为迥异:

var a = [1, 2, 3]
var b = a
var c = a

println("a === a: \\(a === a), b === c: \\(b === c)");

结果为:

a === a: false, b === c: false

这应该是编译器的一个 BUG。


以上是关于[Swift] 数组恒等 === 的 bug?!的主要内容,如果未能解决你的问题,请参考以下文章

从Swift看Objective-C的数组使用

从Swift看Objective-C的数组使用

swift swift_bug.swift

Swift 5.5 爆严重堆栈损坏 BUG

汉语-词语:恒等

Swift Bug 清单已迁移至 Github 中