[swift-dev] Optional to String conversion

Dmitri Gribenko gribozavr at gmail.com
Sat Dec 5 00:05:10 CST 2015


On Fri, Dec 4, 2015 at 10:00 PM, Andrew Trick <atrick at apple.com> wrote:
> I’m adding runtime functionality to support optional casts and ran into some Optional to String conversion behavior that is currently somewhat accidental—it will break when I add functionality. I want to understand the desired behavior before doing extra work to fix it.
>
> Currently swift does this:
>
>> print(Int?(3))
> Optional(3)
>> print(String?("meow"))
> Optional("meow")
>
> I think swift should do this:
>
>> print(Int?(3))
> 3
>> print(String?("meow"))
> "meow"
>> debugPrint(Int?(3))
> Optional(3)
>> debugPrint(String?("meow"))
> Optional("meow")
>
> When a value already knows how to represent itself as a string, I don't think that the string "Optional" belongs in the textual representation.
>
> When debugging data structures, it makes sense to include the "Optional" indicator.
>
> What was the intention here and what do people think is the desired behavior?

This behavior was not accidental.  Here's the rationale:

If an Optional is nil, it should somehow indicate that.  Whatever the
representation is, it would be engineer-oriented and not suitable for
end users.  Thus, Optional should never be printed to users, it would
only ever be presented to engineers, and thus its print() and
debugPrint() representations should be the same.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/


More information about the swift-dev mailing list