Reputation: 255
I'm looking at code that I've forked on GitHub. There's one function that I'm interested in, particularly for its syntax: it has code within curly braces after calling a SpriteKit function. Here's (basically) what it looks like:
func selectBox(box: GuessingBox) {
// I'll omit the stuff that doesn't relate to my question
box.flip(scaleX: boxEnlargingScale) {
// Scale the box back to the original scale.
box.run(scaleBackAndWait) {
// Check if the round should end.
if !box.isCorrect {
// A failure box is chosen.
self.showAllResults(isSuccessful: false)
}
// Omitted code
}
As you can see, after calling box.flip() and box.run(), there's more code that's inside the curly braces. Since I'm new to Swift, I'd like to know how more about how this syntax works: is it a nested function? Does the code inside the curly braces only run under certain conditions? Or, is it equivalent to simply just typing each line of code in its own separate line, without the curly braces (as shown below)?
box.flip(scaleX: boxEnlargingScale)
box.run(scaleBackAndWait)
if !box.isCorrect {
// ...
}
Upvotes: 0
Views: 52
Reputation: 14824
This syntax may look like a nested function, but it's actually what's known as "trailing closure syntax", and it's an alternative way of passing a closure as a function argument. You've probably seen an example of this with sort()
:
myIntegers.sort { $0 < $1 }
is equivalent to:
myIntegers.sort(by: { $0 < $1 })
As you can now tell, removing the braces would radically change the meaning of the code you're asking about.
Upvotes: 2