我正在尝试创建一个简单的 HTTP 框架。
首先我有以下类型别名:
typealias successBock = ([Any]) -> ()
typealias errorBlock = (NSError) -> ()
typealias requestResponseTuple = (con: NSURLConnection, success: successBock?, error: errorBlock?)
我的这个方法有一个错误:
func performHttpRequest<T>(method: HTTPRequestMethod, path: String?, parameter:Dictionary<String, String>,
success:successBock?, error:errorBlock?) -> Int {
var url = NSURL(string: baseURL.stringByAppendingPathComponent((path != nil) ? path! : ""))
var request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 20.0)
var con = NSURLConnection(request: request, delegate: self, startImmediately: true)
var requestId = newRequestId()
currentActiveRequests[requestId] = requestResponseTuple(con, successBock.self, errorBlock.self)
return requestId;
}
错误在这里:
requestResponseTuple(con, success, errorBlock.self)
错误:“'successBock.Type' 无法转换为 'successBock'”
我想传递该 block ,以便稍后可以调用它。在 Objective-c 中我从未遇到过这样的问题。
说实话,我不知道为什么会发生这种情况。我检查了几页,但没有找到解决方案。
最诚挚的问候,
麦克
编辑2: 改变了一种方法:
func performHttpRequest<T>(method: HTTPRequestMethod, path: String?, parameter:Dictionary<String, String>,
success:successBock?, error:errorBlock?) -> Int {
var url = NSURL(string: baseURL.stringByAppendingPathComponent((path != nil) ? path! : ""))
var request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 20.0)
var con = NSURLConnection(request: request, delegate: self, startImmediately: true)
var requestId = newRequestId()
currentActiveRequests[requestId] = requestResponseTuple(con, success, error)
return requestId;
}
现在错误:找不到接受提供的参数的“下标”重载
编辑:
代码链接: http://pastebin.com/c5a0fn1N http://pastebin.com/d0QGQ2AR
最佳答案
好吧,如果我理解得很好,你只需要改变
requestResponseTuple(con, successBock.self, errorBlock.self)
由
requestResponseTuple(con!, success, error)
您的参数名称是成功和错误。 successBock 和 errorBlock 是类型。 所以我建议你将它们大写。 希望对您有帮助。
编辑:由于 NSURLConnection
返回一个可选值,因此您必须将其解开。
在解开包装之前,您应该检查 con 是否等于 nil。
if let con = NSURLConnection(request: request, delegate: self, startImmediately: true)
{
currentActiveRequests[requestId] = RequestResponseTuple(con, success, error)
}
else
{
// there was an error, the NSURLConnection has not been created
}
关于Swift 闭包作为元组中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923108/