Swift Functions
A function encapsulates a piece of code that performs a specific task, gives it a name, and can then be called repeatedly.
Swift's functions are richer than those in most languages: parameters can have external labels, default values, and a variable number of arguments, and functions themselves can be used as parameters and return values.
This article starts with the most basic definition and call, then gradually covers labels, default values, inout, function types, nested functions, and three commonly used attributes: @escaping, @autoclosure, and @discardableResult.
Definition and Call
Define a function with the func keyword, write parameters in parentheses, and point to the return type with ->.
The function below takes a string and returns a greeting.
Example
import Foundation
// Define the function: write _ before the first parameter to indicate no label is written at the call site
func greet
(
_ name
:
String
)
String
{
return
"Hello, (name)!"
}
// At the call site, pass the value directly without writing name:
(
greet
(
"Runoob"
)
)
The output of the above code is:
Hello, Runoob!
Note:Since Swift 3 (SE-0046),all parameters have external labels by default, and the first parameter is no exception. So func greet(name: String) at the call site you must write it as greet(name: "Runoob"), so writing directly greet("Runoob") will report missing argument label 'name:' in call. "The first parameter has no external label by default" is an old Swift 2 rule that has long been obsolete.
Parameter Labels and Parameter Names
A parameter can have two names: the one written first is theexternal label(used at the call site), and the one written later is theinternal parameter name(used inside the function body).
This design makes the call site read like an English sentence, while short variable names can still be used inside the function body.
Example
import Foundation
// person is the external label, name is the internal parameter name
func greet
(
person name
:
String, from city
:
String
)
String
{
return
"(name) is from (city)"
}
// At the call site you must write person: and from:
(
greet
(
person
:
"Runoob"
, from
:
"www.runoob.com"
)
)
The output of the above code is:
Runoob 来自 www.runoob.com
If you do not want to write a label at the call site, add an underscore _ before the parameter name to explicitly omit it.
| Parameter Positions and Syntax | external label | Declaration and Call Examples |
|---|---|---|
| Normal syntax (the same applies to the first parameter) | The parameter name itself | func f(x: Int) → f(x: 1) |
| Add _ to omit the label | None | func f(_ x: Int) → f(1) |
| Custom external label | Custom labels | func f(label x: Int) → f(label: 1) |
| Second and subsequent parameters | The parameter name itself | func f(a: Int, b: Int) → f(a: 1, b: 2) |
| Parameter with a default value | The parameter name itself | func f(a: Int = 1) → f(a: 2) |
Parameter default values
Once a parameter has a default value, you can omit it at the call site; parameters with default values are usually placed at the end of the parameter list.
Example
import Foundation
// scheme has a default value and can be omitted at the call site
func makeURL
(
host
:
String, scheme
:
String
=
"https"
)
String
{
return
"(scheme)://(host)"
}
(
makeURL
(
host
:
"www.runoob.com"
)
)
(
makeURL
(
host
:
"www.runoob.com"
, scheme
:
"http"
)
)
The output of the above code is:
https://www.runoob.com
http://www.runoob.com
Note:A parameter with a default value automatically gets an external label identical to its parameter name. Even if it is the first parameter, you must write the label at the call site:
Example
import Foundation
// name has a default value and automatically gets the external label name
func greet
(
name
:
String
=
"Runoob"
)
String
{
return
"Hello, (name)!"
}
(
greet
(
)
)
(
greet
(
name
:
"RUNOOB"
)
)
The output of the above code is:
Hello, Runoob!
Hello, RUNOOB!
Variable arguments (varargs)
Adding three dots ... after the parameter type indicates that this parameter can accept any number of values of the same type.
A variadic parameter is an array inside the function body; it can be omitted, in which case the array is empty.
Example
import Foundation
// numbers is a variadic parameter and can accept any number of Int values
func sum
(
_ numbers
:
Int...
)
Int
{
var total
=
0
for
n in numbers
{
total
=
n
}
return
total
}
(
sum
(
1
,
2
,
3
,
4
,
5
)
)
(
sum
(
)
)
The output of the above code is:
15
0
A function can have at most one variadic parameter, and it cannot use any special syntax beyond an external label.
inout Parameters
Function parameters are constants by default; they cannot be changed inside the function and cannot affect external variables.
To let a function modify a variable passed in, declare the parameter as inout and add & before the variable at the call site.
Example
import Foundation
// Both parameters are marked inout, so modifications inside the function affect external variables
func swapValues
(
_ a
:
inout Int, _ b
:
inout Int
)
{
let temp
=
a
a
=
b
b
=
temp
}
var x
=
1
var y
=
2
swapValues
(
&
x,
&
y
)
(
"x=(x), y=(y)"
)
The output of the above code is:
x=2, y=1
Note:inout The parameter requires exclusive access. Passing the same variable to two inout parameters at once, for example swapValues(&x, &x), the compiler will report an error directly: inout arguments are not allowed to alias each other (inout parameters are not allowed to alias each other).
Function type
Every function has its own type, composed of its parameter types and return type, for example (Int, Int) -> Int.
A function type can be used to declare variables just like a normal type.
Example
import Foundation
// Declare a function-type variable: takes two Int values and returns an Int
let mathFunction
:
(
Int, Int
)
Int
=
{
$
0
$
1
}
(
mathFunction
(
3
,
4
)
)
The output of the above code is:
7
A function whose return type is Void has the type () -> Void, which can also be written without the arrow as () -> ().
Functions as Parameters and Return Values
Since a function type is a type, it can naturally be passed as a parameter and also returned as a result.
As a parameter
The caller hands the "how to do it" to the function, and the function is only responsible for calling it at the appropriate time.
Example
import Foundation
// operation is a parameter of function type
func apply
(
_ value
:
Int,
using
operation
:
(
Int
)
Int
)
Int
{
return
operation
(
value
)
}
// Pass in a closure that squares its parameter
(
apply
(
5
,
using
:
{
$
0
$
0
}
)
)
The output of the above code is:
25
As a return value
Returning a function lets the caller decide later which operation to use.
Example
import Foundation
// The return type is (Int, Int) -> Int
func chooseOperation
(
_ op
:
String
)
(
Int, Int
)
Int
{
switch
op
{
case
"add"
:
return
{
$
0
$
1
}
case
"mul"
:
return
{
$
0
$
1
}
default
:
return
{
_, _ in
0
}
}
}
let add
=
chooseOperation
(
"add"
)
(
add
(
10
,
20
)
)
The output of the above code is:
30
Nested functions
A function can be defined inside another function; such a function is called a nested function.
A nested function is by default visible only inside the outer function and is often used to keep helper logic together.
Example
import Foundation
func chooseStepFunction
(
backward
:
Bool
)
(
Int
)
Int
{
// stepForward and stepBackward are functions nested inside another function
func stepForward
(
_ input
:
Int
)
Int
{
return
input
1
}
func stepBackward
(
_ input
:
Int
)
Int
{
return
input
1
}
return
backward
?
stepBackward
:
stepForward
}
(
chooseStepFunction
(
backward
:
true
)
(
10
)
)
(
chooseStepFunction
(
backward
:
false
)
(
10
)
)
The output of the above code is:
9
11
@escaping Escaping Closures
Parameters of function type are by defaultnon-escaping: the closure must finish executing before the function returns.
If a closure needs to be stored and called after the function returns, it must be marked @escaping.
Example
import Foundation
// Use a class to store the closure, avoiding global mutable state
class
HandlerStore
{
var stored
:
(
(
)
Void
)
?
// @escaping indicates that the closure escapes the function's scope and is stored
func store
(
_ action
:
@escaping
(
)
Void
)
{
stored
=
action
}
}
let store
=
HandlerStore
(
)
store.
store
{
(
"Escaping closure executes later"
)
}
store.
stored
?
(
)
The output of the above code is:
逃逸闭包稍后执行
Escaping closures often cause retain cycles when capturing self; the solution can be found in the capture list of article 33, 《Swift Automatic Reference Counting》.
@autoclosure Auto-closures
@autoclosure automatically wraps the passed expression into a closure, so the call site can omit one level of braces.
Its value lies indeferred evaluation: the expression is evaluated only when it is actually used.
Example
import Foundation
// @autoclosure automatically wraps the expression into a closure
func logIfTrue
(
_ condition
:
@autoclosure
(
)
Bool
)
{
if
condition
(
)
{
(
"Condition is true"
)
}
}
// At the call site, write the expression directly, no need to write { 1 < 2 }
logIfTrue
(
1
<
2
)The output of the above code is:
条件为真
The standard library's && and || use this feature, so the right-hand expression is evaluated only when needed, which is what makes short-circuiting work.
@discardableResult
When a function has a return value but the call does not receive it, the compiler issues a warning.
In places where the return value is genuinely not needed, mark the function with @discardableResult and the warning disappears.
Example
import Foundation
// @discardableResult allows callers to ignore the return value without producing a warning
@discardableResult
func increase
(
_ value
:
inout Int
)
Int
{
value
=
1
return
value
}
var counter
=
0
increase
(
&
counter
)
increase
(
&
counter
)
(
counter
)
The output of the above code is:
2
Common questions
Below are a few of the most commonly confused questions about function parameters and closure attributes.
Do you need to write parameter labels at the call site?
Look at the declaration. Since Swift 3, all parameters use their parameter names as external labels by default, and the first parameter is no exception; only positions where _ is written in the declaration do not require a label.
If _ is written in the declaration, you must not write a label; if a custom label is written, you must use that label.
Should you choose inout or a return value?
When a function produces only one result, prefer a return value, which is clearer semantically and has no side effects.
Use inout only when you genuinely need to modify a variable passed in by the caller, or need to modify several variables at once.
Why must closure parameters sometimes be marked @escaping?
Without @escaping, the compiler guarantees that the closure is used up before the function returns, which allows stricter optimization and checking.
Once a closure is stored in a property, placed into an array, or handed to an asynchronous task, it must be explicitly marked @escaping.
Does @autoclosure make code harder to understand?
Yes. The call site does not reveal that there is a closure here, and misuse can cause the expression to be executed multiple times or deferred.
Use it in public APIs only when deferred evaluation is needed; in everyday code, writing a closure directly is more intuitive.