Swift generic operator -
i wrote class one:
struct size { var width:double=0 var height:double=0 init(width:double=0,height:double=0) { self.width=width self.height=height } [...] }
now want ability divide size number, , use generics function each type convertible double. example int, cgfloat, float
but when insert function:
func /<t>(lhs:size,rhs:t)->size { return size(width:lhs.width/double(rhs),height:lhs.height/double(rhs)) }
i error
error: cannot invoke 'init' argument list of type '(width: double, height: double)' return size(width:double(lhs.width/rhs),height:double(lhs.height/rhs)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
that weird because list passed of exact types defined in class (double)..
if rewrite in way:
func /<t>(lhs:size,rhs:t)->size { let drhs=double(rhs) return size(width:lhs.width/drhs,height:lhs.height/drhs) }
then error:
error: cannot invoke 'init' argument of type 't' let drhs=double(rhs) ^~~~~~~~~~~
which weirder because swift library file has got lot of initializers double, int, or float types:
extension double { init(_ v: uint8) init(_ v: int8) init(_ v: uint16) init(_ v: int16) init(_ v: uint32) init(_ v: int32) init(_ v: uint64) init(_ v: int64) init(_ v: uint) init(_ v: int) } extension double { init(_ v: float) init(_ v: float80) }
what wrong in code?
in swift generics require type safety done constraining through protocols. better in c++ safety cannot assumed generics. usually, can use protocols standard library implement these generics unfortunately in case need define special protocol , extend types want able use. i've done int , float can same thing types want use.
protocol doubleconvertible { func todouble() -> double } extension int : doubleconvertible { func todouble() -> double { return double(self) } } extension float: doubleconvertible { func todouble() -> double { return double(self) } } func /<t : doubleconvertible>(lhs: size, rhs: t) -> size { return size(width: lhs.width / rhs.todouble(), height: lhs.height / rhs.todouble()) }
the reason have manually because none of standard library protocols (that know of) define requirement such numbers can converted double.
Comments
Post a Comment