简体   繁体   中英

The closure in Swift

I just started to use Swift in my project. When reading the instruction of Alamofire library, I found some code like:

extension Request {
    class func XMLResponseSerializer() -> Serializer {
        return { (request, response, data) in
            if data == nil {
                return (nil, nil)
            }

            var XMLSerializationError: NSError?
            let XML = ONOXMLDocument.XMLDocumentWithData(data, &XMLSerializationError)

            return (XML, XMLSerializationError)
        }
    }

    func responseXMLDocument(completionHandler: (NSURLRequest, NSHTTPURLResponse?, OnoXMLDocument?, NSError?) -> Void) -> Self {
        return response(serializer: Request.XMLResponseSerializer(), completionHandler: { (request, response, XML, error) in
            completionHandler(request, response, XML, error)
        })
    }
}

In the second function responseXMLDocument I wonder why we have to rewrite the closure. If the parameter of the function is already a closure, why cannot we just write like:

return response(serializer: Request.XMLResponseSerializer(), completionHandler:completionHandler)

I tried it but it does not compile.

It occurred to me just after I posted my question... The problem is that the type of the parameter does not match. More specific, it is the XML parameter, which should be AnyObject?, is OnoXMLDocument? in the inner handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM