Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift, How to understand the "inline closure"?

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!

like image 324
Viton Zhang Avatar asked Feb 13 '17 03:02

Viton Zhang


People also ask

What is inline closure in Swift?

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 .

How does closure work in Swift?

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.

What is closure in Swift with example?

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.

What is $0 and $1 in Swift?

$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.


1 Answers

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.

like image 155
Alexander Avatar answered Jan 04 '23 15:01

Alexander