小编Chr*_*ood的帖子

具有约束类型的Swift协议扩展约束到集合,不能使用下标

我正在尝试编写符合集合协议的协议,它有一个associatedType - Object和一个属性对象.

protocol DDCDataSource: Collection
{
    associatedtype Object
    var object: Object {get set}
}
Run Code Online (Sandbox Code Playgroud)

我想为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)
    }
}
Run Code Online (Sandbox Code Playgroud)

generics swift swift-protocols protocol-extension swift3.2

3
推荐指数
1
解决办法
584
查看次数