gpt4 book ai didi

swift - MutableCollection 与 RangeReplaceableCollection

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:46 25 4
gpt4 key购买 nike

来自 Apple's MutableCollection API reference :

The MutableCollection protocol allows changing the values of a collection’s elements but not the length of the collection itself. For operations that require adding or removing elements, see the RangeReplaceableCollection protocol instead.

但是,MutableCollection 需要以下下标:

subscript(bounds: Range<Self.Index>) -> Self.SubSequence { get set }

这不允许更改集合的长度吗?例如,我们不能用一个空范围和一个非空子序列来调用这个下标的 setter 吗?

最佳答案

简答:

如果你有一个 MutableCollection 的变量type 然后你必须只用一个范围调用下标 setter 和一个具有相同长度的新切片。某些符合 MutableCollection 的类型(例如 Array)允许不同长度的替换来插入或删除元素,但一般来说,可变集合不需要这样做。

特别是 MutableCollection默认实现如果范围和新切片的长度不同。

更长的答案:

首先请注意,您不必实现

public subscript(bounds: Range<Index>) -> MutableSlice<Self>

在你自己的集合中,因为它有一个默认实现协议(protocol)扩展。正如人们在 source code 中看到的那样在该方法中,下标 setter 调用一个

internal func _writeBackMutableSlice()

实现的功能here .该函数首先从切片到目标范围,然后验证下标范围和新切片的长度是否相同:

_precondition(
selfElementIndex == selfElementsEndIndex,
"Cannot replace a slice of a MutableCollection with a slice of a smaller size")
_precondition(
newElementIndex == newElementsEndIndex,
"Cannot replace a slice of a MutableCollection with a slice of a larger size")

所以你不能通过改变MutableCollection的长度(默认)下标 setter ,尝试这样做将中止程序。

举个例子,让我们定义一个符合以下条件的“最小”类型可变集合:

struct MyCollection : MutableCollection, CustomStringConvertible {

var storage: [Int] = []

init(_ elements: [Int]) {
self.storage = elements
}

var description: String {
return storage.description
}

var startIndex : Int { return 0 }
var endIndex : Int { return storage.count }

func index(after i: Int) -> Int { return i + 1 }

subscript(position : Int) -> Int {
get {
return storage[position]
}
set(newElement) {
storage[position] = newElement
}
}
}

然后用相同长度的切片替换集合的一部分作品:

var mc = MyCollection([0, 1, 2, 3, 4, 5])
mc[1 ... 2] = mc[3 ... 4]
print(mc) // [0, 3, 4, 3, 4, 5]

但对于不同的长度,它会因运行时异常而中止:

mc[1 ... 2] = mc[3 ... 3]
// fatal error: Cannot replace a slice of a MutableCollection with a slice of a smaller size

请注意,符合MutableCollection 的具体类型可能允许在其下标 setter 中进行不同长度的替换,例如 Array 就是这样。

关于swift - MutableCollection 与 RangeReplaceableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38033512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com