I want to write extensions for more than one protocol and found this posting which was very interesting, but I wasn't able to follow Matthew Seaman completely.
In this case I want to write my own extension BinaryNumber
which I want to add to BinaryInteger
and BinaryFloatingPoint
. But when I try to add my protocol, Xcode shows the error message Extension of protocol 'BinaryInteger' (or 'BinaryFloatingPoint') cannot have an inheritance clause.
Here is my code:
protocol BinaryNumbers {} // my protocol
extension BinaryNumbers {
func foo() -> Void {
print("It works!")
}
}
// try to extend Swift protocols
extension BinaryInteger : BinaryNumbers {} // doesn't work
extension BinaryFloatingPoint : BinaryNumbers {} // doesn't work
//Updade
@sweeper suggested to extend Numeric
, so I tried, but get an error.
extension Numeric {
func foo() -> Bool {
return self <= 127
// Referencing operator function '<=' on 'BinaryInteger' requires
// that 'Self' conform to 'BinaryInteger'
}
}
When I extend BinaryInteger
and BinaryFloatingPoint
one by one, it works.