我想用给定类型实例化一个对象。这是对该函数的调用:
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
}
}
最佳答案
参见: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
}
关于swift - 如何实例化给定类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36179254/