[swift-evolution] Auto Unwrapping Of Optionals

Alan Skipp al_skipp at icloud.com
Sat Apr 30 16:39:14 CDT 2016

> On 29 Apr 2016, at 15:37, Tod Cunningham via swift-evolution <swift-evolution at swift.org> wrote:
> This concept of Auto Unwrapping of Optionals is similar to Implicitly Unwrapped Optionals, but is only applied when the compiler knows it is safe to do so.
> Take the following example:
> class Test {
>    var today: NSDate? = nil
>    func test() {
>        today = today ?? NSDate()
>        print("Today is \(today)")   // Would be printed as an optional
>        let timeInterval: NSTimeInterval = today!.timeIntervalSinceNow  // Requires ! or (if let) to unwrap
>        // ... do stuff with timeInterval ...
>    }
> }

I can’t say I’m keen on adding further compiler magic to Optionals, each special case adds further complication to the concept.

An alternative take on the example code posted would be: should the property be an Optional? If there is an Optional property which can later be replaced with a default value (today = today ?? NSDate()), perhaps the property should have been assigned the default non-optional value to begin with? Avoiding having to deal with the ceremony of Optionals all together.

I appreciate that the example code you posted was a succinct way to demonstrate the use case you had in mind and not meant as a `real world` case, but it does highlight that if a property has a valid default value, it probably shouldn’t be an Optional. The great thing about Optionals is that there’s the choice to avoid them as much as possible : )

More information about the swift-evolution mailing list