我想用给定的Type实例化一个Object。这是对函数的调用:
buildObjetFromType("data", typeClass: User.self)
这是功能代码:
public static func buildObjectFromType<T>(data: String, typeClass: T.Type) -> T{
print(typeClass) // will print "User"
var object:T?
object as! T.Type // cast the object into an User -> NOT WORKING !
// fill the object with the data, knowing
// return the object once it has been filled with the data.
}
这是我的用户类:
public class User {
private var id:String?
private var login:String?
private var pwd:String?
private var nom:String?
private var prenom:String?
public required init(){
id = ""
login = ""
pwd = ""
nom = ""
prenom = ""
}
public convenience init(_login: String, _pwd: String){
self.init()
login = _login
pwd = _pwd
}
public convenience init(_id: String, _login: String, _pwd: String, _nom: String, _prenom: String){
self.init(_login: _login, _pwd: _pwd)
id = _id
nom = _nom
prenom = _prenom
}
}
答案 0 :(得分:2)
请参阅:Instantiate an object of a generic type in Swift
假设您要实例化的所有类都具有不带参数的必需初始化程序(您可能希望它们从相同的基类继承,并将此要求添加到您的函数中),您可以执行以下操作:
static func instantiate<T where T: BaseClass>(data: String, cls: T.Type) -> T {
let obj = T()
// do something with obj and data
}