- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
来自 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 theRangeReplaceableCollection
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/
我找不到有关如何符合 MutableCollection 的文档. Google 在该主题上完全空白。 示例,我想为 GMSPath 添加一致性/GMSMutablePath : import Cor
来自 Apple's MutableCollection API reference : The MutableCollection protocol allows changing the valu
我正在尝试为 MutableCollection 写一个扩展需要利用 sort(by:)排序方法,但它似乎不适用于 MutableCollection扩展,尽管此方法是为 MutableCollect
我正在尝试扩展 Array所以我可以镜像数组数组的内容,但编译器说我不能调用 reverse()在数组中的元素上,尽管 reverse()在 MutatingCollection 中定义协议(prot
我有一个文件,其中有 2 个不同的扩展名: extension MutableCollection where Indices.Iterator.Element == Index { } extens
我正在尝试使用 kotlin 创建一个 MutableList,但我收到一条错误消息: 类型推断失败。预期类型不匹配:推断类型为 MutableList 但预期为 MutableCollection
我是一名优秀的程序员,十分优秀!