[swift-evolution] Auto Unwrapping Of Optionals
Haravikk
swift-evolution at haravikk.me
Sat Apr 30 02:22:15 CDT 2016
> On 29 Apr 2016, at 23:28, Rod Brown via swift-evolution <swift-evolution at swift.org> wrote:
>
> I agree that it's a pain to have to unwrap after this, but this proposal worries me somewhat.
>
> I don't think we can safely guarantee that the value is non-null outside a very limited subset of cases, and we're breaking the simple, general and reasonable syntax of Swift for a very minor convenience win.
>
> Additionally, this will play out like magic. Suddenly an optional starts dynamically changing its behaviour. I can't see where the compiler begins or ends the assertion of the value's non-null state, and so you have code that, with a little shifting around, begins to fail to even compile, based on something the user cannot see.
>
> I think we have better mechanisms to handle this type of thing, like the if/guard let syntax, and implicitly unwrapped optionals.
Actually, thinking about it a bit more I think that the main case where I would want something like this is actually, something more like the following:
if var unwrappedFoo = self.foo {
unwrappedFoo.mutate() // self.foo is unchanged, we have to do this:
self.foo!.mutate() // original is changed, but unwrappedFoo is not
// foo was changed once, not twice
}
Of course classes follow different rules, but it’s a little counter-intuitive for structs, what if we could do something like this:
if inout unwrappedFoo = self.foo {
unwrappedFoo.mutate() // both are changed
self.foo!.mutate() // no longer required this
// foo was changed twice, and both forms are consistent
}
i.e- inout in this case gets us a non-optional reference to the original value, not a copy (or potential copy). In the event that self.foo is changed somewhere else, unwrappedFoo would continue to reference to what it used to be and remain usable, though of course in the above example the call to self.foo! would fail in such a case, but it should no longer be required.
At least in my experience this is the most common case that I encounter, as I try to use if let or guard let (or var) for safety, but then this doesn’t help when manipulating a struct, so a third option could be useful in such cases.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160430/c7ce8b46/attachment.html>
More information about the swift-evolution
mailing list