[swift-evolution] Auto Unwrapping Of Optionals

David Sweeris davesweeris at mac.com
Sat Apr 30 15:31:08 CDT 2016


> On Apr 30, 2016, at 7:18 AM, Rod Brown via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I think this specific proposal asking for compiler magic to auto-unwrap invisibly and only in very limited cases, as this proposal suggests, ends up breaking a lot more than it fixes. I can only see circumstances of this working with variables in the current scope, as anything like a property could be updated by other methods, threads etc, and the compiler couldn't be certain of state.
> 
> I think a language feature like you describe would be a lot more helpful, but I'd love to hear others' views on that.
> 
> - Rod


Yeah, auto-unwrapping "wherever it might be possible" seems too magical to me. I wouldn’t object to the compiler auto-unwraping optionals within a well defined code block, though:
//foo is T?
if foo != nil {
//foo is T within this set of curly braces
}
But even that invokes a bit of compiler magic, in that for this one type of enum (`Optional`), the compiler knows that if it isn’t one case, it must be the other. I’d prefer a more general solution…

What if the “is” keyword could function as a kind of incomplete switch?
var foo: UnicodeDecodingResult
...
if foo is .Result {
    //since we know foo is a result, `foo` refers to foo's associated or raw value within this set of curly braces
}
This allows the language feature (and relevant compiler code paths) to be used with any enum, not just Optionals. The “optional unwrapping behavior" could then be written like this:
var bar = 4 as Int?
...
if bar is .Some {
    //bar is 4 within this set of curly braces
}

- Dave Sweeris

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


More information about the swift-evolution mailing list