我已经阅读了多篇关于 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

在上面的代码中,我从 index-2 (i.e 3) 中删除了 arr 中的元素。Index-2 也是 startIndexslice
当我打印 slice[slice.startIndex] 时,它​​仍然打印 3。

由于没有为 ArraySlice 创建额外的存储空间,那么 Array 中的任何更改为什么没有反射(reflect)在 ArraySlice 中?

文章/帖子可以在这里找到:

https://dzone.com/articles/arrayslice-in-swift

https://marcosantadev.com/arrayslice-in-swift/

最佳答案

ArrayArraySlice 都是值类型,这意味着在

var array = [0, 1, 2, 3, 4, 5]
var slice = array[0..<2]
arrayslice 是独立的值,改变一个不会影响另一个:
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 {

    // ...
  }

这还不是完整的实现,但(希望)已经证明了
(mutating) remove(at:) 方法将元素存储复制到一个新的
缓冲区 if 是共享的(与另一个数组或数组切片)。

我们还可以通过打印元素存储基地址来验证:
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

如果数组、字典或字符串使用相同的“写时复制”技术
被复制,或者 StringSubstring 共享存储。

因此,数组切片与其原始切片共享元素存储
数组,只要它们都没有发生突变。

这仍然是一个有用的功能。这是一个简单的例子:
let array = [1, 4, 2]
let diffs = zip(array, array[1...]).map(-)
print(diffs) // [-3, 2]
array[1...] 是给定数组的 View /切片,没有实际复制
要素。

向下传递切片(左半部分或右半部分)的递归二进制搜索函数将是另一个应用程序。

10-08 06:07