Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Closures

Swift Closures

A closure is a block of code that can be passed around and used like a value, and it can capture and store variables from its defining context.

In Swift, global functions, nested functions, and closure expressions are all essentially closures, differing only in form and naming.

This article explains the simplification of closure expressions, trailing closures, capture semantics, and the two error-prone concepts of escaping and non-escaping closures.


Three forms of closures

Swift officially divides closures into three forms; they have the same capabilities but different shapes.

form Syntax Feature
Global functions func name(...) { } Named, and capture no values
Nested functions Defined inside another function Named, and can capture variables of the outer function
Closure expressions { ... } Unnamed, written with lightweight syntax, and able to capture context

Closure expression syntax

A closure expression is wrapped in a pair of braces, with parameters and return type written before in and the body after in.

The full form is { (parameters) -> ReturnType in statements }.

Example

import Foundation

// Full form: parameter list, return type, and the in keyword are all required

let full

=

{

(

a

:

Int, b

:

Int

)

Int in

   

return

a

b

}

print

(

full

(

3

,

4

)

)

The output of the above code is:



7

Simplification through type inference

When the closure's type is already known, both the parameter types and the return type can be omitted.

Example

import Foundation

// With the type annotation on the left, the right side can omit parameter types and return type

let inferred

:

(

Int, Int

)

Int

=

{

a, b in a

b

}

print

(

inferred

(

3

,

4

)

)

The output of the above code is:



12

Shorthand arguments with $0 and $1

Parameter names can also be omitted, using $0 for the first parameter, $1 for the second, and so on.

When the closure body is a single line, even return can be omitted.

Example

import Foundation

// $0 is the first parameter, $1 the second

let shorthand

:

(

Int, Int

)

Int

=

{

$

0

$

1

}

print

(

shorthand

(

10

,

4

)

)

The output of the above code is:



6

Note:Shorthand is concise but becomes hard to read with many parameters. With more than two, it is better to write named parameters again.

Operator functions

Swift's operators are essentially functions, so an operator such as < can be passed directly as a closure.

Example

import Foundation

let numbers

=

[

3

,

1

,

4

,

1

,

5

,

9

,

2

,

6

]

// Pass the < operator directly as a closure

let sorted

=

numbers.

sorted

(

by

:

<

)

print

(

sorted

)

The output of the above code is:



[1, 1, 2, 3, 4, 5, 6, 9]


Trailing closures

When a closure is the last argument of a function, it can be written outside the function call's parentheses; this is called a trailing closure.

A trailing closure removes one level of parentheses, making the code read more like a "configuration block".

Example

import Foundation

let numbers

=

[

3

,

1

,

4

,

1

,

5

,

9

,

2

,

6

]

// Trailing closure: the closure is written outside the function call's parentheses

let evens

=

numbers.

filter

{

$

0

%

2

==

0

}

print

(

evens

)

The output of the above code is:



[4, 2, 6]

Multiple trailing closures

When a function has multiple closure parameters, the first may omit its label, but the others must be labeled.

This form is common in APIs with two callbacks, "success / failure".

Example

import Foundation

// Two closure parameters: the first uses a trailing closure, the second a labeled trailing closure

func load

(

from source

:

String, onSuccess

:

(

)

Void, onFailure

:

(

)

Void

)

{

   

if

source.

hasPrefix

(

"https"

)

{

        onSuccess

(

)

   

}

else

{

        onFailure

(

)

   

}

}

load

(

from

:

"https://www.runoob.com"

)

{

    print

(

"Loading succeeded"

)

}

onFailure

:

{

    print

(

"Load failed"

)

}

The output of the above code is:



加载成功


Capturing values

A closure can capture variables and constants from outside its definition, and these values persist even after the defining function has returned.

The count below is captured by the returned closure, and each call increments it by one from its previous value.

Example

import Foundation

// The returned closure captures the external count variable

func makeCounter

(

)

(

)

Int

{

    var count

=

0

   

return

{

        count

=

1

       

return

count

   

}

}

let counter

=

makeCounter

(

)

print

(

counter

(

)

)

print

(

counter

(

)

)

print

(

counter

(

)

)

The output of the above code is:



1

2

3


Closures are reference types

Assigning a closure to another variable does not copy the captured values; both variables point to the same closure and the same state.

Example

import Foundation

func makeCounter

(

)

(

)

Int

{

    var count

=

0

   

return

{

        count

=

1

       

return

count

   

}

}

// A closure is a reference type; counterA and counterB point to the same closure

let counterA

=

makeCounter

(

)

let counterB

=

counterA

print

(

counterA

(

)

)

print

(

counterB

(

)

)

The output of the above code is:



1

2

The second print shows 2, indicating that both calls share the same count.


Capture lists [weak self] and [unowned self]

When storing a closure in a property of a class, the closure strongly references self, which easily creates a retain cycle.

A capture list is written before the parameter list to specify how values are captured, thereby breaking the cycle.

[weak self]

weak is a weak reference: after the object is deallocated it automatically becomes nil, so it must be unwrapped before access.

Example

import Foundation

class

Downloader

{

    var site

=

"RUNOOB"

    var onFinish

:

(

(

)

Void

)

?

    func start

(

)

{

       

// [weak self] makes the closure reference self weakly, avoiding a retain cycle

        onFinish

=

{

[

weak self

]

in

            guard let self

else

{

return

}

            print

(

"Download complete: (self.site)"

)

       

}

   

}

    deinit

{

        print

(

"Downloader deallocated"

)

   

}

}

var downloader

:

Downloader

?

=

Downloader

(

)

downloader

?

.

start

(

)

downloader

?

.

onFinish

?

(

)

downloader

=

nil

The output of the above code is:



下载完成:RUNOOB

Downloader 被释放

Because a weak reference is used, setting downloader to nil allows the object to be deallocated normally.

[unowned self]

unowned also does not increase the reference count, but it assumes the object is always alive, so no unwrapping is needed on access.

If the object has already been deallocated but is still accessed, the program crashes immediately; therefore it is only suitable for relationships whose lifetimes are guaranteed not to diverge.

Example

import Foundation

class

TimerOwner

{

    var seconds

=

0

   

// [unowned self] does not increase the reference count and produces no optional

    lazy var tick

:

(

)

Int

=

{

[

unowned self

]

in

        self.

seconds

=

1

       

return

self.

seconds

   

}

}

let owner

=

TimerOwner

(

)

print

(

owner.

tick

(

)

)

print

(

owner.

tick

(

)

)

The output of the above code is:



1

2

Note:When unsure which to use, choose [weak self] and pair it with guard let self else { return }. It is safer, at the cost of just one optional unwrapping.


Escaping and non-escaping closures

Function-type parameters are non-escaping by default: the closure is guaranteed to finish executing before the function returns.

Comparison of escaping and non-escaping closures: a non-escaping closure finishes executing and is released before the function returns, while an escaping closure is stored in a property and called only after the function returns

A closure that must be stored and called after the function returns must be marked @escaping.

Comparison Item Non-escaping closures Escaping closures
Whether an annotation is needed No Requires @escaping
Lifetime Finishes before the function returns Can outlive the function call
Whether it can be stored in a property or array No You can
Requirements when referencing self Just write it directly In a class you usually need to write self explicitly and consider a capture list

Example

import Foundation

// Non-escaping: the closure finishes executing before the function returns

func perform

(

_ action

:

(

)

Void

)

{

    action

(

)

}

perform

{

    print

(

"Non-escaping closure executed immediately"

)

}

// Escaping: the closure is stored in a property and called after the function returns

class

Store

{

    var stored

:

(

(

)

Void

)

?

    func save

(

_ action

:

@escaping

(

)

Void

)

{

        stored

=

action

   

}

}

let store

=

Store

(

)

store.

save

{

print

(

"Escaping closure executes later"

)

}

store.

stored

?

(

)

The output of the above code is:



非逃逸闭包立即执行

逃逸闭包稍后执行


Common questions

Below are a few common questions about closure syntax and capture semantics.

What's the difference between a closure and a function

They're essentially the same. A function is a closure with a name; a closure expression is an anonymous, more lightweight closure.

Both can capture context, and both can be passed as arguments and return values.

When must you write self

When writing an escaping closure inside an instance method of a class or struct, Swift requires you to write self explicitly, reminding you of a possible retain cycle.

In non-escaping closures it can usually be omitted, and the code compiles either way.

Can trailing closures be nested

Yes, but nesting too deeply hurts readability; consider extracting the inner closure into a named function or a separate variable.

Why do variables captured by a closure stay alive

When a closure captures a variable, it holds on to it; as long as the closure itself is still referenced, the captured variable won't be destroyed.

This is also the root of possible memory leaks caused by closures; see article 33 《Swift Automatic Reference Counting》。