Nevin
1
Is there a fundamental reason that we cannot mix-and-match assignment and variable declaration when destructuring a tuple?
Suppose we have integer variables x and y, and we want to perform x += y while also checking for overflow.
Ideally this could be done in a single line, like so:
(x, let overflow) = x.addingReportingOverflow(y)
However that does not compile.
Instead, today we must split it up into two lines like this:
let overflow: Bool
(x, overflow) = x.addingReportingOverflow(y)
Or this:
let (sum, overflow) = x.addingReportingOverflow(y)
x = sum
Is there a realistic possibility of allowing the one-line version to work?
11 Likes
it seems that in this case you are running into this because we are missing an addReportingOverflow(_:) method on FixedWidthInteger. if addingReportingOverflow(_:) had an inplace counterpart like this, like many of the other numeric APIs do, you could simply do
let overflow:Bool = x.addReportingOverflow(y)
1 Like
Nevin
3
That is not the point of the post. I am not looking for alternative ways to solve the specific example.
I am asking if there is a fundamental reason that Swift cannot have both assignment and variable declaration intermixed within the destructuring of a single tuple.
(That said, I would certainly support the API you suggest.)
1 Like
since you already defined a general syntax-level transformation for this, i doubt there is a fundamental reason why this can’t be done. i’ve been implementing a lot of language extensions recently using the new package plugins feature, so i’m pretty confident someone could create a syntax-level language extension to do just that, where the tool in question would “compile” this down to standard swift.
i just think that 9 times out of 10, this kind of problem is better solved with an appropriate in-place mutating method.
1 Like
bnyu
(Bnyu)
5
+1
(Golang allows this behavior at function return using := , but it can not mixed assign outer scope variable with variable declaration, it will become all variable declaration(shadow). I just think that is not intuitive)
So I like this simple syntax.