ios - Swift: Self type, subclassing and overriding methods -


the following code shows class superclass of class b. function has return type 'self'. overridden method in class b courses error (see comment).

class {     class func dosomething(param1: string) -> self {         var entity = self()          // code goes here...          return entity     } }  class b: {     override class func dosomething(param1: string) -> self {         var entity = super.dosomething(param1) as! b          // code goes here...          return entity // error:'b' not convertible 'self'     } } 

if have used instancetype in objective-c work. how can working? or not possible?

i want have method return type of current overriding class. workaround have init-method accepts superclass type parameter.


that brings question: object casted current class isn't equal self()?

so difference between

var entity = someobject as! b 

and

var entity = self() // current class / file b 

edit:

class func objectcast<t: a>(obj: a) -> t {     return obj as! t } 

returning objectcast(entity) instead of entity works.

class {     class func dosomething(param1: string) -> self {         var entity = self()          // code goes here...          return entity     } }  class b: {     override class func dosomething(param1: string) -> self {         var entity = super.dosomething(param1) as! b          // code goes here...          return objectcast(entity) // no error.     } } 

so… why need trick, seems i've problem understanding meaning of 'self'. can answer second part of question difference?

regarding second question, difference first option return b in subclass , subclasses won't return self, while second option return entity of self in subclass. if mark class b final both approaches work.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -