【发布时间】:2017-07-15 10:47:59
【问题描述】:
我如何创建一个具有另一个通用协议类型的通用协议?
在我的示例中,我有一个 Heap,它是一个泛型类型的协议,因为我的堆中可以有任何符合 Comparable 协议的元素。
所以在我的priorityQueue中,我也想将它作为一个协议(为了避免代码重复和练习)我希望我的priorityQueue包含一个Heap.T等于PriorityQueue.Item的堆,但我不不知道该怎么做。有什么想法吗?
当然我可以用“抽象类”来做,但这不是重点。
顺便说一句,下面的代码甚至无法编译
代码:
public protocol PriorityQueuable: Hashable {
associatedtype KeyType: Comparable
associatedtype ValueType: Comparable
var key: KeyType { get set }
var value: ValueType { get set }
}
protocol Heap {
associatedtype T: Comparable
var data: [T] { get set }
mutating func heapify(parentIndex: Int)
}
protocol PriorityQueue {
associatedtype Item: PriorityQueuable
//FIXME: doesn't allow me to do that. Why?
var heap: Heap<Item> { get set }
// doesn't compile as well
// var heap: Heap { get set }
}
【问题讨论】:
-
如果将
PriorityQueue设为Heap的子类会怎样? -
由于 Swift 中的数据结构主要是结构体,我想将优先级队列具体实现为结构体。但是由于不允许继承结构,所以我决定不考虑这个选项。 + 这是学习该语言的新机会
-
尝试用泛型类包装
Heap -
@paper1111 还有其他方法吗?
-
@denis631 你的意思是包装
Heap还是什么?
标签: swift generics interface protocols