swift - instancetype parameters type in closure/callback for subclasses -


say have asynchronous task grab array of instances so:

class func fetchlistofinstances(callback: ([mysuperclass])->()) {     // long task asynchronously , call callback } 

and used so:

mysubclass.fetchlistofinstances() { mylist in // mylist inferred [mysuperclass]      whatever in mylist {          let typeireallywant = whatever as! mysubclass          // stuff here each instance of typeireallywant      } } 

swift seems pretty clever types i'll surprised if if there's not way this, couldn't find google search:

class func fetchlistofinstances(callback: ([self])->()) {     // long task asynchronously , call callback } 

...

mysubclass.fetchlistofinstances() { mylist in // mylist inferred [mysubclass]      whatever in mylist {          // stuff here each instance of whatever      } } 

it may not possible, thought worth ask.

according 'self' available in protocol or result of class method , use self generic type seems you're after not possible. instead use function, example:

func fetchinstances<t: mysuperclass>(callback: [t] -> void) {     // long task asynchronously , call callback. } 

at point in function above you're going creating instance of t. in case you'll need required initialiser in mysuperclass; meaning subclasses of mysuperclass must implement initialiser. example:

class mysuperclass {     required init(arg: string) {         // ...     } } 

you can use t(arg: "...") in fetchinstances because know t implements init(arg: string).

finally, call fetchinstances, explicitly stating type of mylist swift knows type t is.

fetchinstances { (mylist: [mysubclass]) in     // ... } 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -