swift - How do I get the instance from a Generic? -


i cannot understand why causes errors (errors shown comments in code):

class someclass {     var id = 123 }  class anotherclass {     func myfunc<t>(object: t) {         t.id = 555 // error: type 't' has no member 'id'         object.id = 555 // error: value of type 't' has no member 'id'     } }  let someclass = someclass() let anotherclass = anotherclass() anotherclass.myfunc(someclass) 

how instance of someclass after passing generic function?

also, can't named downcasting inside anotherclass (as expect generic).

you have little bit more generics. t has no member called id - correct! because pass in some t has member (someclass) not matter compiler since @ other point can insert else int or [double] or anything.

consider adding following line code

anotherclass.myfunc(1) 

what should happen? should .id do??? fail because 1 not have member called id.

your t has no generic constraint telling compiler anything, therefore assumes can pass in anything. , can use properties possible inputs share.

what might want use example

func myfunc<t : someclass>(object: t) {     object.id = 555 } 

that tells compiler allowed pass in objects of type someclass or classes extend someclass. following logic above compiler can @ code, possible inputs , allows perform operations valid on possible inputs. therefore compiler knows id property exists since someclass has , classes extending someclass well, since how extending works.

once again apple docs on generics place learn lot generics basics quite complex use-cases.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -