我学习 Swift 一段时间了,也阅读了 Swift 语言指南。
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94
闭包的概念对我来说是新的。我想我可以理解如何使用它,但是我可以在哪里使用它呢?它有什么好处呢?
我用谷歌搜索并得到答案Swift 中何时使用闭包?
我认为答案并不令人满意。语言指南写了这么多,我猜这是该语言的一个非常重要的特性,也许它在框架中被广泛使用。
谁能给我展示更多例子来展示它的力量?
多谢。
这个问题可能有点宽泛,但我会尝试回顾一下。
参考文档:
闭包是可以传递的独立功能块
周围并在您的代码中使用。
当您想要将一段代码作为参数传递给想要异步执行的方法时,您应该使用闭包。
为了使它更简单 - 通过给出一个现实世界的例子 - 想象有一个方法负责扫描用户的照片,因此该方法应该返回一个照片数组和另一个视频数组:
伪代码:
// the method should scan the the user's photos and return them after fetching is finished
// the 'completion' (success) closure should returns two arrays
// what if there is something wrong happened? another closure should returns an error
// for the example purposes they are arrays of strings, the error is also a string
func scanPhotos( completion: @escaping (_ photos: [String], _ videos: [String]) -> (), failure: @escaping (String) -> ()) {
// imagine that the scanning has been successfully done and you filled the two arrays:
//if scanningSuccess {
let fetchedPhotos = [String]()
let fetchedVideos = [String]()
completion(fetchedPhotos, fetchedVideos)
//} else {
// if something goes wrong
failure("the error!!")
//}
}
调用方法:
scanPhotos(completion: { (photos, videos) in
// now you can use the fetched photos and videos
}, failure: { error in
// display an alert -for example- based on the error is saying...
})
请注意,扫描过程应异步执行,完成后,应执行两个块(成功或失败)之一。
一些与闭包配合使用的流行方法:
- animateWithDuration:动画:完成:
- urlSession(_:dataTask:didReceive:completionHandler:)
- 排序方式:)
AGAIN:这只是闭包的简单用法;您需要查看文档以了解更多详细信息。
我希望它有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)