I'm a newbie that is learning Swift from SwiftLanguageGuide-Concurrency and feel confused while reading codes:
listPhotos(inGallery: "Summer Vacation") { photoNames in
let sortedNames = photoNames.sorted()
let name = sortedNames[0]
downloadPhoto(named: name) { photo in
show(photo)
}
}
What's the param inGallery
for? It seems never be used inner function.
And what is the photoNames
? Does it another param of listPhotos
?
Anyone could explain this for me? Thanks a lot :)
CodePudding user response:
listPhotos(inGallery: "Summer Vacation") { photoNames in
let sortedNames = photoNames.sorted()
let name = sortedNames[0]
downloadPhoto(named: name) { photo in
show(photo)
}
}
In the above code listPhotos is a function , whose last parameter is a closure, by closure you can assume
when the function performs some action and gets a value, this value can then be passed on to the closure which is a function type itself, which can then use it and perform another action and return it.
in what cases this is useful, well , you must have seen @escaping attribute , what it does , is that if we are fetching data from network, we wait for the data to come and then pass it to the closure which will run only after the function has fetched a value
so closure are really simple
a block of code that waits to get some value after a portion of function has run and then uses it
you see here
photoNames in
let sortedNames = photoNames.sorted()
photosNames is the value that the function got back and passed it to closure to use and perform further operations, hope it helps