如何解决符合协议时,类型化声明的冗余复制
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 举报,一经查实,本站将立刻删除。