4

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?

4

1 回答 1

3

我不相信有一种用于同时绑定的let语法var

有趣的是,你可以这样做switch

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

但是(var a, let b) = pair(或类似的变体)似乎是不可能的。

于 2015-01-31T12:51:13.080 回答