Swift - how do I pass a type/object (name or instance) into a method and then (a) get the type (b) instantiate it? -


i need this, i'm having sorts of problems:

class myclass { }  class someclass {   func callmethod(object) {     let thetype = object.type // need same result myclass.self     let newinstance = object() // need same result myclass()   } }  let someclass = someclass() let object = myclass someclass.callmethod(object) 

how this?

i want able specify 1 type (e.g. myclass). can either type name or instance of , 2 values shown in code comments.

it lot easier if passed in 2 separate variables, i'm sure can in one.

you can use .dynamictype property of instance type. can call required init method on (or other class/static method).

let thetype = object.dynamictype let newinstance = thetype.init() 

note: code compiles, depending on type of object. if type has required init() method, safe call on dynamictype. however, appears if type nsobject compiler let call init() on dynamictype though subclass may or may not have init() method given how swift initializer inheritance works. arguably bug in compiler, use code caution if choose so. @nhgrif discussion on topic.


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 -