math - return Int from a generic mathematics type in swift -
how require generic type usable in mathematical operations mentioned here
which led me protocol
protocol mathematicsprotocol : equatable { init(_ value: int) init(_ value: float) init(_ value: double) func + (lhs: self, rhs: self) -> self func - (lhs: self, rhs: self) -> self func * (lhs: self, rhs: self) -> self func / (lhs: self, rhs: self) -> self } extension int: mathematicsprotocol {} extension float: mathematicsprotocol {} extension double: mathematicsprotocol {}
used in snippet
struct myrange<datatype : mathematicsprotocol> { let start : datatype let end : datatype let step : datatype subscript(index: int) -> datatype { { assert(index < self.count) return start + datatype(index) * step } } var count : int { return int((end-start)/step) //not working // return 4 } }
however conversion of datatype int in count function doesn't work. there way fix this?
edit: works, it's ugly hack using string temporary value.
func convert<datatype : mathematicsprotocol>(value : datatype) -> int { let intermediate = "\(value)" nsstring return intermediate.integervalue }
you have define how mathematicsprotocol
converted int
, e.g. adding intvalue
property protocol:
protocol mathematicsprotocol { // ... var intvalue : int { } } extension int: mathematicsprotocol { var intvalue : int { return self } } extension float: mathematicsprotocol { var intvalue : int { return int(self) } } extension double: mathematicsprotocol { var intvalue : int { return int(self) } }
then can use as
var count : int { return ((end-start)/step).intvalue }
Comments
Post a Comment