问题描述
protocol PathCollection: Collection where Element == Target.Element,Index == Target.Index {
associatedtype Target: Collection
static var reference: KeyPath<Self,Target> { get }
}
extension PathCollection {
private var target: Target { self[keyPath: Self.reference] }
var startIndex: Index { target.startIndex }
var endIndex: Index { target.endIndex }
subscript(index: Index) -> Element {
get { target[index] }
}
func index(after i: Index) -> Index {
target.index(after: i)
}
}
这是非常有用的协议,可帮助我们在创建自定义集合时减少样板代码。
假设我们的结构包装了一个字典。我们希望它像字典一样成为一个集合。
我们应该为字典属性提供keyPath并应用于协议。而且有效!
用法示例和我的问题:
protocol Graph: PathCollection where Target == [String: Int] {
var storage: [String: Int] { get set }
}
extension Graph {
static var reference: KeyPath<Self,[String: Int]> { \.storage }
}
struct UndirectedGraph: Graph {
typealias Element = Dictionary<String,Int>.Element // Why should we again declare this typealias!?
typealias Index = Dictionary<String,Int>.Index // Why should we again declare this typealias!?
var storage: [String: Int]
}
它完美地工作。但是,为什么我们要重新声明Element和Index类型别名!?在本文的第一行代码中,我们显式定义了Element和Index:
protocol PathCollection: Collection where Element == Target.Element,Index == Target.Index {
然后:
protocol Graph: PathCollection where Target == [String: Int] {
如果删除该重新声明,则会出现编译错误,我不理解:
“ PathCollection”需要类型“ Slice”和 'Dictionary
.Element'(aka'(键:字符串,值:Int)')被 等价
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)