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

Harlan Haskins harlan at harlanhaskins.com
Tue Oct 4 07:35:51 CDT 2016


I would say it's surprising if you don't expect the value to be optional. Swift is such that you can write very long programs without knowing yourself the static type of every variable. It just takes one Optional property of a non-optional struct passed into a string interpolation segment to cause this behavior, as Keith showed earlier with url.absoluteString. This is especially bad because APIs are being notated with optionality, like in the Swift 2.2 -> 2.3 shift, that were previously implicitly unwrapped.

I think a warning is the best way to go here. A developer probably didn't intend to interpolate an optional (I've never personally wanted the behavior) and this lets them know.

- Harlan

> On Oct 4, 2016, at 8:31 AM, Jeremy Pereira <jeremy.j.pereira at googlemail.com> wrote:
> 
> 
>> On 3 Oct 2016, at 22: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”.
> 
> On the other hand, when I interpolate an optional, I want it to be obvious that it is an Optional. If I didn’t want Optional(foo) in the string, I would unwrap it first. 
> 
> I also disagree with the proposal that the behaviour is surprising. What else would you expect? 
> 
> Having said that, I have no objection to the proposed warning.
> 
> 
>> 
>> -Kevin
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 



More information about the swift-evolution mailing list