swift - Pass Metatype as function argument -


in swift can following:

struct employee{     var name:string     var age:int }  // metatype let currenttype = employee.self // concrete instance let instancefromtype = currenttype.init(name: "jessie", age: 54)  print(instancefromtype) // prints employee(name: "jessie", age: 54) 

currenttype metatype: means pass struct name (eg. person, etc.) , instancefromtype contain struct of type.

but, suppose want pass currenttype function argument , then, inside body of function, create instancefromtype: how do?

i tried one:

func f(m:any.type){    let instancefromtype = m.init(name: "jessie", age: 54)   print(instancefromtype) }  f(m:currenttype) 

but get:

'init' member of type; use 'type(of: ...)' initialize new object of same dynamic type

what doing wrong? appreciated.

[update]

i forgot mention found 1 working, can't understand why:

protocol proto {     init(name:string,age:int) }  struct employee:proto{     var name:string     var age:int     init(name:string,age:int){         self.name = name         self.age = age     } }  let currenttype = employee.self  func f(m:proto.type){      let instancefromtype = m.init(name: "jessie", age: 54)     print(instancefromtype)  }  f(m:currenttype) 

you cannot call m.init(name: "jessie", age: 54) arbitrary type m, because type not have such initializer.

what can define protocol type can initialized arguments, , restrict argument of f accordingly:

protocol initializablefromnameandage {     init(name: string, age: int) }  func f(type: initializablefromnameandage.type) {     let instance = type.init(name: "jessie", age: 34)     print(instance) } 

then declare protocol conformance types

struct employee: initializablefromnameandage {     var name:string     var age:int } 

and

let currenttype = employee.self f(type: currenttype) 

works expected.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -