Swift 闭包作为元组中的字段

Swift Closures as field in Tuple

我正在尝试创建一个简单的 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'”

我想传递块,以便以后可以调用它。 在 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;
}

现在出错:无法为 'subscript' 找到接受提供的参数的重载

编辑:

代码链接: http://pastebin.com/c5a0fn1N http://pastebin.com/d0QGQ2AR

好的,如果我理解得很好,你只需要更改

requestResponseTuple(con, successBock.self, errorBlock.self)

来自

requestResponseTuple(con!, success, error)

您的参数名称是成功和错误。 successBock 和 errorBlock 是类型。 所以我建议你把它们资本化。 希望对你有帮助。

编辑:因为 NSURLConnection returns 是可选的,所以你必须打开它。 在展开它之前,你应该检查 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
        }