generics - Swift - how to declare a method which receives a number in a range -
i want create function has number parameter should between 0..100 %
i thought best way enforce creating wrapper type using floatingpointtype
protocol , getting compilation error
protocol 'floatingpointtype' can used generic constraint because has self or associated type requirements
struct percent { init(val : floatingpointtype) { // enforce value between 0..100 } } func hideview(percent : percent) { // percent 0..100 @ point .. work here }
what correct way enforce condition @ compile time?
the easiest way define type holds double
(or float
or int
) in required range:
struct p { let val : double init (val : double) { // ... } }
but if want treat different floating point types have define generic class
struct percent<t : floatingpointtype> { let val : t init(val : t) { self.val = val } }
to compare values need require equatable
well:
struct percent<t : floatingpointtype t: equatable> { let val : t init(val : t) { if val < t(0) { self.val = t(0) } else if val > t(100) { self.val = t(100) } else { self.val = val } } }
example:
let p = percent(val: 123.4) println(p.val) // 100.0
note requires hideview()
generic well:
func hideview<t>(percent : percent<t>) { // percent.val has type `t` , in range // t(0) ... t(100) }
Comments
Post a Comment