【发布时间】:2017-09-09 08:10:15
【问题描述】:
我正在尝试编写一个符合 Collection Protocol 的协议,它有一个 associatedType - Object 和一个 property 对象。
protocol DDCDataSource: Collection
{
associatedtype Object
var object: Object {get set}
}
我想为 Object 也符合 Collection 协议的情况添加一些默认功能,即直接返回 Object 对这些必需的 Collection 属性和函数的实现。除了 Collection 对下标的要求之外,这一切似乎都有效。
不能用“Self.Object.Index”类型的索引为“Self.Object”类型的值下标
extension DDCDataSource where Object: Collection
{
typealias Index = Object.Index
var startIndex: Object.Index {
get {
return object.startIndex
}
}
var endIndex: Object.Index {
get {
return object.endIndex
}
}
subscript(position: Object.Index) -> Element
{
return object[position]
}
func index(after i: Object.Index) -> Object.Index {
return object.index(after: i)
}
}
【问题讨论】:
-
请不要使用图片,而是添加代码sn-p。
-
我添加了标签 swift 3.2 因为它是 Xcode 9 特有的。在 Xcode 8 上你会有 "Use of undeclared type 'Element'".
-
extension DDCDataSource where Object: RandomAccessCollection,感觉好多了。 -
return object[position] as! Element -
@Cœur:不,这会在运行时崩溃。
标签: swift generics swift-protocols protocol-extension swift3.2