我已经定义了一些响应模型作为如何使用泛型推断类型?
class UserProfile{
var name:String = "Anish"
var age:Int = 20
}
class StudentProfile:UserProfile{
var std_id:Int = 1
}
我对Web API请求类作为
class WebCaller{
class func callWebService<T>(responseType:T.Type,completionHandler:(T)->()){
let model = StudentProfile() as! responseType//wont compile here
completionHandler(model)
}
}
,我想打电话给作为
WebCaller.callWebService(responseType: StudentProfile.self){ responseModel in
//response model should automatically infer the type
print(responseModel.name)
print(responseModel.age)
print(responseModel.std_id)
}
现在,如果我想呼叫为
WebCaller.callWebService(responseType: UserProfile.self){ responseModel in
//this should automaticaly infer the type
print(responseModel.name)
print(responseModel.age)
}
但是这可以通过使用AnyObject类型
class func callWebService<T>(responseType:T.Type,completionHandler:(AnyObject)->())
,但我需要它转换为我的效应初探type.What我试图acheieve是我的API调用者应该给我的类型,这样我不应该投完成它在我的ViewModel
为什么不这样'让模型= StudentProfile()的! T'解决你的问题? – Bilal
是的,但...是要走的路? – Costello