[swift-evolution] [Proposal draft] Disallow Optionals in String Interpolation Segments

Kevin Ballard kevin at sb.org
Mon Oct 3 17:49:50 CDT 2016


On Mon, Oct 3, 2016, at 03:18 PM, Jordan Rose wrote:
>
>> On Oct 3, 2016, at 14:41, Kevin Ballard via swift-evolution <swift-
>> evolution at swift.org> wrote:
>>
>> On Mon, Oct 3, 2016, at 10:52 AM, Harlan Haskins via swift-
>> evolution wrote:
>>> Swift developers frequently use string interpolation as a
>>> convenient, concise syntax for interweaving variable values with
>>> strings. The interpolation machinery, however, has surprising
>>> behavior in one specific case: Optional<T>. If a user puts an
>>> optional value into a string interpolation segment, it will insert
>>> either "Optional("value")" or "nil" in the resulting string. Neither
>>> of these is particularly desirable, so we propose a warning and fix-
>>> it to surface solutions to these potential mistakes.
>>
>> Is there any way we could instead allow Optionals but just print
>> them the way we print ImplicitlyUnwrappedOptionals? That's almost
>> always how I want my Optionals to work when interpolating. To be
>> specific, this means for .some(x) we just print x, and for .none we
>> print "nil".
> We had this at one point, but we took it out because people would
> forget to test the nil case. I think `?? ""` or `?? nil` really is the
> best answer here.

But you can't write that, unless you're dealing specifically with an
Optional<String>.  If you try you'll get an error:

unnamed.swift:2:19: error: binary operator '??' cannot be applied to
operands of type 'Int?' and 'String'
    print("x: \(x ?? "nil")")
                ~ ^  ~~~~~
unnamed.swift:2:19: note: overloads for '??' exist with these partially
matching parameter lists: (T?, @autoclosure () throws -> T), (T?,
@autoclosure () thro
ws -> T?)
    print("x: \(x ?? "nil")")
                  ^
This leads to writing code like "… \(x.map(String.init(describing:)) ??
"nil")" which is pretty gross.

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


More information about the swift-evolution mailing list