Allow default value to inout parameter

228 Views Asked by At

The title might be a little confusing, so let me break this to you.

In Swift, we can have functions with default parameter values, e.g:

func foo(value: Int = 32) { }

And we also can have In-Out parameters, e.g.

func foo(value: inout Int) { }

But, there is a way to have both? A inout parameter, that if it wasn't passed, we can create? This is particularly useful with recursive functions, and I am trying to figure this out.

1

There are 1 best solutions below

0
On

Default parameters are mostly just a convenient shorthand for overloads. When you want to move beyond the basics, you just build the overload by hand, which allows you any level of complexity you want:

// The base-case version
func foo() {
    var value = 0
    foo(value: &value)
}

func foo(value: inout Int) { }

As a side note, be very careful with recursion in Swift. There's no tail-call optimization, so you can blow up the stack if the recursion is deep. The lack of elegant pattern matching makes recursive code much less elegant, and passing values by inout makes things harder on the optimzer. In most cases you'll want a loop (or to hide the loop in a higher-order non-recursive function like map).

Also, don't forget about nesting functions, which is helpful for hiding accumulator-style parameters.

func foo() {
    var value = 0

    func f() {
        // operate on value and recurse
        // no need for inout; and doesn't leak the implementation detail
    }

    f()
}