我正在使用AlamoFire进行API调用,并在我的项目中使用类似的东西:
static func login(userName: String, password: String) -> User {
let parameters = ["userName": userName , "password": password]
let user = User()
Alamofire.request(.POST, "myserver.com/login", parameters: parameters, encoding: .JSON)
.validate()
.responseObject { (response: Response<User, NSError>) in
switch response.result {
case .Success(let value):
user.valueHandle?(value)
case .Failure(let error):
user.errorHandle?(error)
}
}
return user
}
(请参阅https://stackoverflow.com/a/37949671/406322了解我如何提出上述代码)。
问题是我有很多除User以外的对象,并且代码重复只有对象的类型不同,所以我试图创建一个泛型方法,如下所示:
static func sendRequest<T>(method: Alamofire.Method, urlString: String, parameters: [String: AnyObject]?) -> T {
let response : T
Alamofire.request(method, urlString, parameters:parameters)
.validate()
.responseObject { (response: Response<T, NSError>) in
switch response.result {
case .Success(let value):
response.valueHandle?(value)
case .Failure(let error):
response.errorHandle?(error)
}
}
return response
}
但斯威夫特抱怨道:
Cannot convert value of type '(Response<T, NSError>) -> ()' to expected argument type 'Response<_, NSError> -> Void'
这是我可以这样做的事情:
User.swift
static func login(userName: String, password: String) -> User {
let parameters = ["userName": userName, "password": password]
return sendRequest<User>(.GET, "http://myserver.com/users", parameters)
}
并在我的调用代码中:
User.login(txtUserName.text!, password: txtPassword.text!)
.success { (value) in
var user = value as! User
//do something with user
}
.error { (error) in
//show error
}
我做得不对?
答案 0 :(得分:3)
您可以使用BaseObject轻松完成此任务:
class BaseUser: ResponseObjectSerializable {
var valueHandle : ((BaseUser)->())?
var errorHandle : ((NSError)->())?
required init?(response: NSHTTPURLResponse, representation: AnyObject) {
}
}
func sendRequest<T:BaseUser>(method: Alamofire.Method, urlString: String, parameters: [String: AnyObject]?) -> T {
let res : T
Alamofire.request(method, urlString, parameters:parameters)
.validate()
.responseObject { (response: Response<T, NSError>) in
switch response.result {
case .Success(let value):
res.valueHandle?(value)
case .Failure(let error):
res.errorHandle?(error)
}
}
return res
}
class
可以保存句柄,使用baseobj你不需要使用协议一次又一次地写它们