我已经阅读了多篇关于 ArraySlice
如何在 `Swift 中使用 Array
的帖子和文章。
但是,我找不到的是它在内部是如何工作的? ArraySlice are Views on Arrays 到底是什么意思?
var arr = [1, 2, 3, 4, 5]
let slice = arr[2...4]
arr.remove(at: 2)
print(slice.startIndex) //2
print(slice.endIndex) //5
slice[slice.startIndex] //3
在上面的代码中,我从 arr
中删除了 index-2(即 3)
处的元素。
Index-2
也是slice
的startIndex
。
当我打印 slice[slice.startIndex]
时,它仍然打印 3。
既然没有为 ArraySlice
创建额外的存储空间,那么为什么 Array
中的任何更改都不会反射(reflect)在 ArraySlice
中?
文章/帖子可以在这里找到:
最佳答案
Array
和ArraySlice
都是值类型,这意味着之后
var array = [0, 1, 2, 3, 4, 5]
var slice = array[0..<2]
array
和 slice
是独立的值,改变一个不会影响另一个:
print(slice) // [0, 1]
array.remove(at: 0)
print(slice) // [0, 1]
这是如何实现的是 Swift 标准库的实现细节,
但是可以检查源代码以获得一些想法:在
Array.swift#L1241
我们找到 Array.remove(at:)
的实现:
public mutating func remove(at index: Int) -> Element {
_precondition(index < endIndex, "Index out of range")
_precondition(index >= startIndex, "Index out of range")
_makeUniqueAndReserveCapacityIfNotUnique()
// ...
}
使用
@inlinable
@_semantics("array.make_mutable")
internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() {
if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) {
_copyToNewBuffer(oldCount: _buffer.count)
}
}
沿着这条路,我们在 ArrayBuffer.swift#L107 找到了
/// Returns `true` iff this buffer's storage is uniquely-referenced.
@inlinable
internal mutating func isUniquelyReferenced() -> Bool {
// ...
}
这还不是完整的实现,但(希望)已经证明了这一点
(变异)remove(at:)
方法将元素存储复制到一个新的
如果是共享缓冲区(与另一个数组或数组切片)。
我们也可以通过打印元素存储基地址来验证:
var array = [0, 1, 2, 3, 4, 5]
var slice = array[0..<2]
array.withUnsafeBytes { print($0.baseAddress!) } // 0x0000000101927190
slice.withUnsafeBytes { print($0.baseAddress!) } // 0x0000000101927190
array.remove(at: 0)
array.withUnsafeBytes { print($0.baseAddress!) } // 0x0000000101b05350
slice.withUnsafeBytes { print($0.baseAddress!) } // 0x0000000101927190
如果数组、字典或字符串使用相同的“写时复制”技术
被复制,或者如果 String
和 Substring
共享存储。
因此,数组切片与其原始元素共享元素存储 数组只要它们都没有突变。
这仍然是一个有用的功能。这是一个简单的例子:
let array = [1, 4, 2]
let diffs = zip(array, array[1...]).map(-)
print(diffs) // [-3, 2]
array[1...]
是给定数组的 View /切片,没有实际复制
要素。
将切片(左半部分或右半部分)向下传递的递归二进制搜索函数将是另一种应用。
关于arrays - Swift 中的 ArraySlice 内部是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50851461/