How do I define a constrained type in Swift? -
i keep bumping onto problem repeatedly. in real life see sets of numbers represent particular quality have difficulties express them distinct type in swift.
for example percent type. let says want have percent type integers. percent never able go on 100 or below zero.
i express in pure c union, members ranging 0 100. using swift enum underlying value type doesn't seem me correct approach. or it?
let's pick one. bribor interbank interest rate. know range between 0 , 20 percent. number decimal 2 decimal places.
what's correct way deal problem in swift? generics perhaps?
as michael says in comment, this:
struct intpercent { let value : int8 init?(_ v : int) { guard v >= 0 && v <= 100 else { return nil } value = int8(v) } }
(note: use struct, not class base value that)
if lot, can improve little using protocols, so:
protocol restrictedvalue { associatedtype t : comparable static var range : ( t, t ) { } var value : t { set } init() // hack make work } extension restrictedvalue { init?(v: t) { self.init() guard self.range.0 <= v && self.range.1 >= v else { return nil } value = v } } struct intpercent : restrictedvalue { static var range = ( 0, 100 ) var value : int = 0 init() {} }
i don't think can use generics limit base type values.
but bet there better solution - 1 not awezome :-)
Comments
Post a Comment