swift - Providing specialized initializers for a generic struct -
i have simple generic struct defined - requirements stored properties comparable
:
struct bounds<a: comparable> { let lower: let upper: }
however, i'd provide couple of specialized initializers struct, use math operations set properties.
init(value: double, tolerance: percentage) { self.lower = value * ( 1 - tolerance ) self.upper = value * ( 1 + tolerance ) } init(value: measurement, tolerance: percentage) { self.lower = value.value * ( 1 - tolerance ) self.lower = value.value * ( 1 - tolerance ) }
the result should 2 different structs, double
or measurement
.
but how do this?
i can't provide specialized init methods in definition compiler complain double not convertible a
. ok...
i can't provide init methods in individual extensions constrained specific types (where == double
) compiler complains:
same-type requirement makes generic parameter 'a' non-generic
maybe should using protocol both double
, measurement
conform in initialization, seems odd, since bounds
struct should care both conform comparable
.
i feel i'm either missing simple, or trying misguided generics. it, so?
not asking for, possible workaround (swift 3):
extension bounds a: floatingpoint { init(value: a, tolerance: a) { self.lower = value * ( a(1) - tolerance ) self.upper = value * ( a(1) + tolerance ) } } let b = bounds(value: 4.0, tolerance: 0.1) print(b.dynamictype) // bounds<double>
Comments
Post a Comment