everyone. When I read the Closures, there is not a definition for inline closures.
Q1: How to understand inline in "inline closure"?
Q2: What is the different between "inline closure" and normal closure?
Thanks in advance for your help!
In Swift, a closure that's passed to a function can be created inline: performClosure({ print(counter) }) Or, when using Swift's trailing closure syntax: performClosure { print(counter) } Both of these examples produce the exact same output as when we passed myClosure to performClosure .
Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables.
In Swift, a closure is a special type of function without the function name. For example, { print("Hello World") } Here, we have created a closure that prints Hello World . Before you learn about closures, make sure to know about Swift Functions.
$0 and $1 are closure's first and second Shorthand Argument Names (SAN for short) or implicit parameter names, if you like. The shorthand argument names are automatically provided by Swift. The first argument is referenced by $0 , the second argument is referenced by $1 , the third one by $2 , and so on.
An inline value is a value that's used directly, without first being assigned to an intermediate variable. Consider these two examples:
let number = 1
print(number)
Here, 1
is assigned to an intermediate variable, number
, which is then printed.
print(1)
Here, 1
, is an inlined integer literal, which is printed directly.
The same applies to closures.
let evenNumberFilter: (Int) -> Bool = { $0 % 2 == 0 }
print((0...10).filter(evenNumberFilter))
Here, { $0 % 2 == 0 }
is a closure (of type (Int) -> Bool
) that's assigned to the intermediate variable evenNumberFilter
before being used.
print((0...10).filter{ $0 % 2 == 0 })
In this case, { $0 % 2 == 0 }
was used directly. It's an inline closure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With