2017-02-19 222 views
0

我想知道下面的代碼有什麼問題?協議的哈希協議

import Foundation 

enum SliderType: Int { 
    case analog = 1, discrete, highLow 
} 

protocol DataEntry: class, Hashable { 

    var hashValue: Int { get set } // hashable protocol requires this 
    var idx: Int { get set } 
    var category: String { get set } 
    var sliderType: SliderType { get set } 
    var sliderTitle: String { get set } 
    var sliderCurrentValue: Float { get set } 
    var sliderMinValue: Float { get set } 
    var sliderMaxValue: Float { get set } 
} 

func ==(lhs: DataEntry, rhs: DataEntry) -> Bool { 
    return lhs.idx == rhs.idx 
} 

可在該截圖中可以看到,我不斷收到錯誤Protocol 'DataEntry' can only be used as a generic constraint because it has Self or associated type requirements

有誰知道什麼可能是錯在這裏? 你如何實現協議的Hashable協議?

enter image description here

回答

0

==要求lhsrhs是相同類型的。兩者都是DataEntry類型是不夠的,因爲您可以使lhsFooDataEntry,並且rhsBarDataEntry

您需要使用泛型才能執行lhsrhs之間的這種關係。

func ==<T: DataEntry>(lhs: T, rhs: T) -> Bool { 
    return lhs.idx == rhs.idx 
} 
+0

嗯 - 仍然沒有幫助。我一直得到相同的錯誤(即''Protocol'DataEntry'只能用作通用約束,因爲它具有自我或相關類型需求......可能是由於我使相當一些類符合' DataEntry'協議,並且這些可能不屬於可平等協議 - 即使您有介紹泛型的想法!我想我可能不得不考慮爲所有符合'DataEntry'的類創建可平等的工作......或者您有任何其他的想法 – iKK

+0

@iKK什麼代碼導致該錯誤 – Alexander

+1

差不多,無論我用'DataEntry'such,例如另一個協議裏面:??'協議BalancesModel { \t \t FUNC getEntries(_ completionHandler:@escaping( _條目:[DataEntry]) - >無效) }或類內,例如 - 我創建一個屬性:'fileprivat e var entries = [DataEntry]()' – iKK