[swift-evolution] Optional Setting
Jacob Bandes-Storch
jtbandes at gmail.com
Tue Dec 15 21:36:44 CST 2015
On Tue, Dec 15, 2015 at 4:58 PM, Marc Knaup <marc at knaup.koeln> wrote:
> I tend towards -1 for multiple reasons:
>
> - It has little value for local variables. In most cases you want to
> use the value you assign to a local variable and assigning it to an
> optional variable would require a subsequent unwrapping. In most cases
> where local variables are involved "var x = y ?? z" is satisfying as it
> creates a non-optional value iff z is non-optional.
>
> Consider using it multiple times with the same variable
var value = someInitialValue
value ??= fallback1
value ??= fallback2
Of course, this could also be "let value = someInitialValue ?? falback1 ??
fallback2", which isn't necessarily more readable, but arguably better
because it uses let.
> - It seems to be a rare use case that you set a value of an optional
> property which is currently nil and without also using that value directly
> within the same context. Quickly checking my Swift apps reveals only very
> little such use cases.
>
> I think you're right that this is one of the most common cases. Without
this proposal:
if self.property == nil { self.property = newValue [possibly optional] }
if let value = self.property {
// ...
}
or
let value: T
if let v = self.property { value = v }
else { value = newValue [non-optional]; self.property = value }
// ...
With this proposal:
self.property ??= newValue
if let value = self.property {
// ...
}
I think the second is cleaner, but the difference isn't huge. You could
also have ??= return the new value, so you can embed it in a larger
expression/optional-binding, but that's not consistent with any of the
other compound assignment operators.
>
> - Most important though is that such an optional assignment operator
> would work differently from all other assignment operators. The right
> operand would never be executed if the variable being assigned is already
> non-nil. This will likely be unexpected for a lot of developers who expect
> similar behavior like in all other assignments.
>
> I disagree that this would be unexpected. It's consistent with how ??, &&,
and || work. (And now that ++ and -- are going away, it likely matters even
less.)
Anecdotally, I introduced this operator about 4 months ago to a codebase
with ~16,500 lines of Swift. It's been used 4 times.
Jacob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151215/87878089/attachment.html>
More information about the swift-evolution
mailing list