swift - Use Self as generic type -


self can used return type of method:

func dosomething() -> self {} 

is somehow possible use self generic type this?

func dosomething() -> wrapper<self> {} 

example

it nice if subclass christmaspresent , let have wrapped function returns wrappedpresent generic set whatever subclass was.

class christmaspresent {     func wrapped() -> wrappedpresent<self> {         return wrappedpresent(present: self)     } }  class wrappedpresent<t: christmaspresent> {     var present: t      init(present: t) {         self.present = present     } }  class toycar: christmaspresent {}  let wrappedtoycar = toycar().wrapped() // inferred be: wrappedpresent<toycar>  

the vexing paradox in swift this: "swift prefers methods, swift's functions more powerful." swift team knows that, , someday have powerful methods. today not day. there many things you'd express in methods cannot. want can done functions, however.

class christmaspresent {}  struct wrappedpresent<t: christmaspresent> {     let present: t }  func wrap<t:christmaspresent>(present: t) -> wrappedpresent<t> {     return wrappedpresent(present: present); }  class toycar: christmaspresent {}  let wrappedtoycar = wrap(toycar()) // inferred be: wrappedpresent<toycar> 

note if code did compile, might still quite surprised @ result. swift custom types not covariant, wrappedpresent<toycar> not subtype of wrappedpresent<christmaspresent>. if had array of wrapped presents, not put wrapped toycar in it. force using fixed (non-type-parameterized) wrappedpresent type anyway, making question moot. generics , classes not mix might imagine in swift.

if have practical example of problem you'd want solve this, recommend bringing on dev forums. swift team responsive.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -