[swift-evolution] Optional Setting

Al Skipp al_skipp at fastmail.fm
Wed Dec 16 05:12:02 CST 2015


> On 16 Dec 2015, at 00:58, Marc Knaup via swift-evolution <swift-evolution at swift.org> 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.
> 
> 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.
> 
> The remaining cases could expressed like "object.property = object.property ?? …" or using "if object.property == nil { … }".
> While it is true that variable and property name could be very long, this is an unlikely case of an already rare case which decreases the value of the proposed assignment operator even further.
> 
> 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 think these are all very good points. Seems like the only really practical use would be restricted to:
object.property ??= val

Instead of:
object.property = object.property ?? val

Is it worth it for that one scenario? As Marc pointed out, the ?? operator is much more versatile as it can also be used to return a non-optional value.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151216/79997120/attachment.html>


More information about the swift-evolution mailing list