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

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -