【问题标题】:Swift - closure expression syntaxSwift - 闭包表达式语法
【发布时间】:2015-09-10 10:33:26
【问题描述】:

我正在使用 Alamofire 库,我注意到他们使用这种语法

func download(method: Alamofire.Method, URLString: URLStringConvertible, headers: [String : String]? = default, #destination: Alamofire.Request.DownloadFileDestination) -> Alamofire.Request

这需要 4 个参数作为输入,但如果你去 documentation 调用他们使用以下方法的方法

Alamofire.download(.GET, "http://httpbin.org/stream/100") { temporaryURL, response in
let fileManager = NSFileManager.defaultManager()
if let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
    let pathComponent = response.suggestedFilename
    return directoryURL.URLByAppendingPathComponent(pathComponent!)
}
return temporaryURL}

只需要 2 个参数(method:URLString:)我认为参数 headers 是可选的,因为提供了 default 语句。 我不明白Destination 是如何处理的。 你能解释一下关闭是如何处理的吗? 为什么花括号在方法调用之后是打开的,而不是在 URLString param 之后的调用内部?

非常感谢您提供的任何帮助

马可

【问题讨论】:

标签: xcode swift syntax closures alamofire


【解决方案1】:

这是尾随闭合技术

如果方法接受闭包作为最后一个参数

class Foo {
    func doSomething(number: Int, word: String, completion: () -> ()) {

    }
}

您可以按照经典方式调用它:

Foo().doSomething(1, word: "hello", completion: { () -> () in 
    // your code here
})

或者使用尾随闭合技术

Foo().doSomething(1, word: "hello") { () -> () in 
    // your code here
}

结果是一样的,只是语法更优雅(恕我直言)。

【讨论】:

    猜你喜欢
    • 2017-03-31
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2014-02-21
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多