Swift Generic Protocol Function Parameters -


this seems should work me. trying make rule protocol able performrule on whatever struct adopts rule protocol , return boolean. however, way code cannot access properties on performrule(:value) value parameter. feel missing important concept or buggy. should able copy code below playground see issue yourself.

import foundation  protocol numbercalculation {     var number : nsnumber { set } }  protocol rule {     var invalidmessage : string { set }     func performrule<t>(value: t) -> bool }  struct greaterthanrule : rule, numbercalculation  {     var invalidmessage: string     var number : nsnumber      init(valuemustbegreaterthan value: nsnumber, withinvalidmessage message : string = "") {         number = value         invalidmessage = message     }      func performrule<nsnumber>(value: nsnumber) -> bool {         number.decimalvalue // works          value.decimalvalue // doesn't work         return true     } } 

saying <nsnumber> defines new generic placeholder type in performrule(value:) method, which, you've named nsnumber, shadow foundation's nsnumber class – meaning value: parameter of type your generic placeholder, not foundation's nsnumber.

if want types conforming rule can choose own type parameter of performrule(value:) method – want associated type, not generic placeholder.

protocol numbercalculation {     var number : nsnumber { set } }  protocol rule {      // define associated type conforming types must satisfy     // providing type replace     associatedtype value     var invalidmessage : string { set }     func performrule(value: value) -> bool }  struct greaterthanrule : rule, numbercalculation {      var invalidmessage: string     var number : nsnumber      init(valuemustbegreaterthan value: nsnumber, withinvalidmessage message : string = "") {         number = value         invalidmessage = message     }      // satisfy associated type implicitly annotating type of parameter     // nsnumber – compiler infer value == nsnumber.     func performrule(value: nsnumber) -> bool {         number.decimalvalue // works         value.decimalvalue // works!         return true     } } 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -