Skip to content

Instantly share code, notes, and snippets.

@sinsoku
Last active June 28, 2016 13:50
Show Gist options
  • Select an option

  • Save sinsoku/1c7c776497b4c4ab99adedf8467151b8 to your computer and use it in GitHub Desktop.

Select an option

Save sinsoku/1c7c776497b4c4ab99adedf8467151b8 to your computer and use it in GitHub Desktop.
Swift で Generics を使って Comparable の挙動を変更する
protocol P {
static func eq<T>(_ x: A<T>, _ y: A<T>) -> Bool
static func lt<T>(_ x: A<T>, _ y: A<T>) -> Bool
}
struct A<T: P>: Comparable {}
func == <T>(x: A<T>, y: A<T>) -> Bool {
return T.eq(x, y)
}
func < <T>(x: A<T>, y: A<T>) -> Bool {
return T.lt(x, y)
}
struct Q: P {
static func eq<T>(_ x: A<T>, _ y: A<T>) -> Bool {
print("B: eq")
return false
}
static func lt<T>(_ x: A<T>, _ y: A<T>) -> Bool {
print("B: lt")
return false
}
}
let a = A<Q>()
let b = A<Q>()
print(a == b)
// B: eq
//=> false
print(a < b)
// B: lt
//=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment