2

我有以下结构:

protocol MidiPlayable : Hashable {
    var midiValue: UInt8 { get }
}

struct PercussionSound : MidiPlayable {
    let name: String 
    let type: PercussionType    
}

struct Note : Hashable, MidiPlayable {

    let pitch: Pitch
    let octave: UInt8
    let midiValue: UInt8
}

我想将这些类型作为 Midiplayable 传递给我的播放设备,因为我只需要知道原始值。另外,它们将被放置在集合中,因此 Hashable 是必要的,而且我想比较它们,所以我希望重载运算符 == != < 和 >

我尝试了两种方法(都是免费功能)

func ==(lhs: Self, rhs: Self) -> Bool {
    return lhs.midiValue == rhs.midiValue
}

导致错误'使用未声明的类型'Self''和

func ==(lhs: MidiPlayable, rhs: MidiPlayable) -> Bool {
    return lhs.midiValue == rhs.midiValue
}

导致错误“协议 'MidiPlayable' 只能用作通用约束,因为它具有 Self 或关联的类型要求”

我该如何解决这个问题?

4

1 回答 1

2

我认为你需要这样的东西:

protocol MidiPlayable : Hashable {
    var midiValue: UInt8 { get }
}

extension MidiPlayable {
    var hashValue : Int {
        return midiValue.hashValue
    }
}

func ==<A: MidiPlayable>(lhs: A, rhs: A) -> Bool {
    return lhs.midiValue == rhs.midiValue
}

struct PercussionSound : MidiPlayable {
    let midiValue: UInt8
    let name: String
    let type: PercussionType
}

struct Note : Hashable, MidiPlayable {
    let midiValue: UInt8
    let pitch: Pitch
    let octave: UInt8
}
于 2015-09-23T21:00:37.043 回答