[swift-evolution] Optional assignment operator

Haravikk swift-evolution at haravikk.me
Fri May 13 05:09:31 CDT 2016


Yeah, as previously discussed you’d usually be better doing something like:

	struct Foo {
		var value:Int?

		func someMethod() {
			let value = self.value ?? 0 // This is no longer optional
			…
		}
	}

Since you end up with a non-optional version to work with, which this operator wouldn’t do (requiring you to unwrap it to use it anyway). To make the operator be as useful it would have to implicitly shadow the variable that it’s being assigned to, which would be strange and require some syntax of its own to be clear; in effect the ?? operator already has all the information you need as shown above, it’s a little longer but it’s more self-documenting so I think it covers the use-cases of an optional assignment pretty well.

> On 12 May 2016, at 23:12, Chris Lattner via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On May 12, 2016, at 2:38 PM, Tod Cunningham via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> I ended up creating a ??= operator about a month ago to do something very similar.  It’s a shame it won’t be made part of the official library.  Although, it is very easy to add.
>> 
>> 
>> Just like the ?? operator the default value is only evaluated if the optional in nil.  However, unlike ?? it will
>> 
>> change the optional to be equal to the value on the right, iff the optional was nil.
> 
> We formally discussed & rejected this already:
> http://article.gmane.org/gmane.comp.lang.swift.evolution/7694
> 
> -Chris
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160513/0b942d50/attachment.html>


More information about the swift-evolution mailing list