swift - checking if generic Type is of s specific Type inside class -
assuming have following protocol , class:
protocol numeric { } extension float: numeric {} extension double: numeric {} extension int: numeric {}  class numericprocessor<t:numeric> {     var test:t     func processstring(stringvalue: string?)         if t double {             test = double(stringvalue)         }     } }   what want convert string spesific t:numeric.
test = t(stringvalue)   will not work although double(stringvalue), float(stringvalue) work.
if t double {    test = double(stringvalue) }   does not work because t double can`t asked. how possibly approach problem in generic numeric class?
edit
i'm idiot. can add initialiser protocol
protocol numeric {     init?(_ s: string) }  extension float: numeric{}  class numericprocessor<t:numeric> {     var test:t?      func processstring(stringvalue: string?)     {         test = t(stringvalue!)     } }  let n = numericprocessor<float>()  n.processstring("1.5") print("\(n.test)") // prints "optional(1.5)"   original not answer
you can add static function protocol conversion.
protocol numeric {     static func fromstring(s: string) -> self? }  extension float: numeric {     static func fromstring(s: string) -> float?     {         return float(s)     } }  // same pattern int , double  class numericprocessor<t:numeric> {     var test:t?      func processstring(stringvalue: string?)     {         test = t.fromstring(stringvalue!)     }  }  let n = numericprocessor<float>()  n.processstring("1.5") print("\(n.test)") // prints "optional(1.5)"      
Comments
Post a Comment