我目前正在尝试将自定义集合类型更新为 Swift 4.1。但是,当我遵守文档并实现 and 的所有要求时Collection
,RangeReplaceableCollection
Xcode 仍然抱怨我的类型不符合RangeReplaceableCollection
.
这是该问题的mcve(由 Hamish 慷慨提供,谢谢您:)
class Foo<Element : AnyObject> {
required init() {}
private var base: [Element] = []
}
extension Foo : Collection {
typealias Index = Int
var startIndex: Index {
return base.startIndex
}
var endIndex: Index {
return base.endIndex
}
func index(after i: Index) -> Index {
return base.index(after: i)
}
subscript(index: Index) -> Element {
return base[index]
}
}
extension Foo : RangeReplaceableCollection {
func replaceSubrange<C : Collection>(
_ subrange: Range<Index>, with newElements: C
) where Element == C.Element {}
}
根据文档,代码应该编译:
要将 RangeReplaceableCollection 一致性添加到您的自定义集合,请添加一个空初始化程序和 replaceSubrange(_:with:) 方法到您的自定义类型。RangeReplaceableCollection 使用此初始化程序和方法提供了所有其他方法的默认实现。
不幸的是,事实并非如此。相反,Xcode 会发出以下错误消息:
// error: type 'Foo<Element>' does not conform to protocol 'RangeReplaceableCollection'
// extension Foo : RangeReplaceableCollection {
// ^
// Swift.RangeReplaceableCollection:5:26: note: candidate has non-matching type '<Self, S> (contentsOf: S) -> ()' [with SubSequence = Foo<Element>.SubSequence]
// public mutating func append<S>(contentsOf newElements: S) where S : Sequence, Self.Element == S.Element
// ^
// Swift.RangeReplaceableCollection:9:26: note: protocol requires function 'append(contentsOf:)' with type '<S> (contentsOf: S) -> ()'; do you want to add a stub?
// public mutating func append<S>(contentsOf newElements: S) where S : Sequence, Self.Element == S.Element
//
为了确保它不是文档中的错误,我检查了 Swift 4.1 的源代码func append<S>(contentsOf newElements: S) where S: Sequence, Element == S.Element
并在 RangeReplaceableCollection.swift 中找到了默认实现,第 442-452 行:
@_inlineable
public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Element {
let approximateCapacity = self.count + numericCast(newElements.underestimatedCount)
self.reserveCapacity(approximateCapacity)
for element in newElements {
append(element)
}
}
问题:
- 尽管提供了默认实现,为什么 Xcode 要求实现此功能?
- 如何让我的代码编译?