2017-07-15 15 views
1

別の汎用プロトコルのタイプを持つ汎用プロトコルを作成するにはどうすればよいですか?genericプロトコルのタイプの変数を持つ汎用プロトコル

私の例では、ヒープには、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 } 
} 
+0

あなたが作る場合は、 '' Heap'のサブクラスをPriorityQueue'何 – Lawliet

+0

スウィフトのデータ構造は、主に構造体であるため、構造体として優先度キューを具体的に実装したいのですが、構造体が継承されないため、このオプションを考慮しないことにしました。 +言語について何かを学ぶ新しい機会です – denis631

+0

ラッピングを試してみてください'Heap'でジェネリッククラス – paper1111

答えて

1

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) 
} 

class AnyHeap<U: Comparable>: Heap { 
    public init(data: [U], heapify: @escaping (_ parentIndex: Int) ->()) { 
     self.data = data 
     self.anyHeapify = heapify 
    } 

    var anyHeapify: (_ parentIndex: Int) ->() 
    var data: [U] 
    func heapify(parentIndex: Int) { 
     self.anyHeapify(parentIndex) 
    } 
} 

protocol PriorityQueue { 
    associatedtype Item: PriorityQueuable, Comparable 

    var heap: AnyHeap<Item> { get set } 
} 

Heapに準拠追加AnyHeapクラスがあることが

ところで、以下のコードでも

コードをコンパイルしません。 AnyHeapは、多型に起因するa Heapである。 (Itemは、これらのプロトコルを実装するプロトコルHeap)に準拠してComparableに準拠していることは非常に簡単であることに注意してください:?

class AQueueable: PriorityQueuable, Comparable { 
    var hashValue: Int { return 1 } 
    var key: String = "Hi" 
    var value: String = "YoMaMa" 
    static func < (lhs: AQueueable, rhs: AQueueable) -> Bool { 
     // implement code 
     return false 
    } 
    static func == (lhs: AQueueable, rhs: AQueueable) -> Bool { 
     // implement code 
     return false 
    } 
} 

class AQueue: PriorityQueue { 
    var heap: AnyHeap = AnyHeap<AQueueable>(data: [AQueueable](), heapify: { parentIndex in 
     // implement code 
    }) 
} 
+0

ありがとう、それは私が避けようとしていたもの、つまりジェネリッククラスを作ることでした。私は汎用プロトコルだけを使って解決したいと思っていました。今すぐスウィフトはそれを許可していないと思われる – denis631

+0

リンゴもAnyDictionariesとAnyArraysを持っているので...あまりにも甘くて美しい... – denis631

関連する問題