[swift-evolution] [Review] SE-0024 "Optional Value Setter `??=`"

Stephen Celis stephen.celis at gmail.com
Wed Feb 17 09:43:58 CST 2016


> On Feb 13, 2016, at 7:10 AM, James Campbell via swift-evolution <swift-evolution at swift.org> wrote:
> 
> One common case could be for a error catching, consider this:
> 
> let object = try? UnsupportedMessage(text: "James", type:.Text, date:NSDate()) ?? FailedObject()
> 
> vs
> 
> var object = try? Message(text: "James", type:.Text, date:NSDate())
> object ??= UnsupportedMessage()
> 
> Why would we need this? I have a chat application where if it gets a message it doesn't understand it will throw an error. In the past I would handle this errors by returning nil like so. However we want to communicate to the user that they missing content by vending a UnsupportedMessage object which shows the UI to prompt them to upgrade.
> 
> If the object being constructed has a lot of variables then it could be lost off the side of the screen. I feel ??= is more concise in this case.

If conciseness is your goal, isn't "??" more concise here? (It's a single line—rather than two—and fewer characters.)

If you're worried about line length and/or readability, have you considered using a newline to break the logic up?

    let object = try? UnsupportedMessage(text: "James", type:.Text, date:NSDate())
        ?? FailedObject()

This way

- the result isn't mutable and
- the result isn't optional

Stephen


More information about the swift-evolution mailing list