Reputation: 63492
Is there any way to describe in Swift an IntegerType
that has a max
property? (something similar to implicit interfaces in go)
There is no protocol to describe a max
attribute, and even if I create one, IntegerType
does not explicitly implement it.
So basically I'm looking for something like:
class Test<T: IntegerType where ?> { // <- ? = something like 'has a "max: Self"' property
}
let t = Test<UInt8>()
or maybe something like:
implicit protocol IntegerTypeWithMax: IntegerType {
static var max: Self { get }
}
class Test<T: IntegerTypeWithMax> {
}
let t = Test<UInt8>()
Upvotes: 2
Views: 698
Reputation: 539815
The Swift compiler does not automatically infer protocol conformance even if a type implements all the required properties/methods. So if you define
protocol IntegerTypeWithMax: IntegerType {
static var max: Self { get }
}
you still have to make the integer types that you are interested in conform to that protocol:
extension UInt8 : IntegerTypeWithMax { }
extension UInt16 : IntegerTypeWithMax { }
// ...
The extension block is empty because UInt8
, UInt16
already have
a static max
method.
Then
class Test<T: IntegerTypeWithMax> {
}
let t = Test<UInt8>()
compiles and works as expected.
Upvotes: 3