exists-forall
exists-forall

Reputation: 4258

Swift: Unpacking a tuple into mutable and immutable variables simultaneously

I have a Swift function which returns a tuple of two values. The first value is meant to usually, but not always, be used as an "updated" version of a piece of mutable state in the caller (I know I could also use inout for this instead of a tuple, but that makes it more annoying to keep the old state while preserving the new one). The second value is a generally immutable return value produced by the function, which is not intended to override any existing mutable state.

Conceptually, the usage looks like this:

var state = // initialize
(state, retval1) = process(state)
(state, retval2) = process(state)
(state, retval3) = process(state)

The problem here, obviously, is that retval1, retval2, and retval3 are never declared, and the compiler gets angry.

state must be a var and must not be redeclared, so I can't write

let (state, retval) = process(state)

However, retval is never modified and should be declared with let as a matter of best practices and good coding style.

I was hoping the following syntax might work, but it doesn't:

(state, let retval) = process(state)

How should I go about unpacking / destructuring this tuple?

Upvotes: 6

Views: 5108

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40965

I don’t believe there’s a syntax for binding with let and var simultaneously.

Interestingly, you can do it in a switch:

let pair = (1,2)
switch pair {
case (var a, let b):
    ++a
default:
    break
}

But (var a, let b) = pair (or similar variants) don’t seem to be possible.

Upvotes: 4

Related Questions