Swift 将元类型作为函数参数传递
在Swift中,我可以执行以下操作:Swift 将元类型作为函数参数传递,swift,struct,metatype,Swift,Struct,Metatype,在Swift中,我可以执行以下操作: 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(n
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是一个元类型:这意味着我可以传递另一个结构名,例如Person等,instanceFromType将包含另一个类型的结构
但是,假设我想将currentType作为函数参数传递,然后在函数体内部创建instanceFromType:我该怎么做
我试过这个:
func f(m:Any.Type){
let instanceFromType = m.init(name: "Jessie", age: 54)
print(instanceFromType)
}
f(m:currentType)
但我得到:
“init”是该类型的成员;使用“typeof:…”初始化同一动态类型的新对象
我做错了什么?感谢您的帮助
[更新]
我忘了提到我发现这一个有效,但我真的不明白为什么:
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)
你不能随意地叫m.initname:Jessie,年龄:54岁
类型m,因为该类型不一定具有这样的
初始化器
您可以做的是为一个类型定义一个协议,该类型可以
从这些参数初始化,并限制参数
相应地,f:
protocol InitializableFromNameAndAge {
init(name: String, age: Int)
}
func f(type: InitializableFromNameAndAge.Type) {
let instance = type.init(name: "Jessie", age: 34)
print(instance)
}
然后为您的类型声明协议一致性
struct Employee: InitializableFromNameAndAge {
var name:String
var age:Int
}
然后
let currentType = Employee.self
f(type: currentType)
正如预期的那样工作。我更新了这个问题只是为了提到这一点,即使我不明白为什么它会如此工作,谢谢@3000:你不明白什么?在函数内部,编译器知道给定类型有一个initname:String,age:Int方法。这就是为什么它不同于您最初的方法。我为此感谢您,我不明白编译器为什么会抱怨,它返回的错误对我来说有点误导。type:of,等等。您为我指明了正确的方向