Jon Colverson Jon Colverson - 3 months ago 8
Swift Question

When are Swift function default parameter values evaluated?

If I give a function parameter a default value that is a not a constant (e.g. the result of a function call) is that value just evaluated once (and if so, when?) or is it evaluated every time the function is called?

Answer

From The Swift Programming Language, under Language Reference > Declarations > Special Kinds of Parameters:

A parameter with an equals sign (=) and an expression after its type is understood to have a default value of the given expression. The given expression is evaluated when the function is called. If the parameter is omitted when calling the function, the default value is used instead.

You can demonstrate this for yourself by putting the following in a playground:

import Foundation

func foo(i: UInt32 = arc4random()) {
    print(i)
}

foo()
foo()
foo()
foo()
foo()

which will print five different random numbers (unless the random number generator generates the same number five times by some astronomically improbable coincidence).

It's not explicit in the docs quoted above, so it's worth noting that when you do specify the argument when calling the function the default expression is not evaluated. You can demonstrate that in a playground too:

func getSomeInt() -> Int {
    print("getSomeInt() was called")
    return 42
}

func bar(_ i: Int = getSomeInt()) {
    print(i)
}

bar(1)

and when that runs you'll see that "getSomeInt() was called" is not printed.

Comments