[swift-evolution] Proposal: String literal suffixes for defining types

Chris Lattner clattner at apple.com
Thu Dec 10 23:52:51 CST 2015

> On Dec 10, 2015, at 11:07 AM, Kevin Ballard via swift-evolution <swift-evolution at swift.org> wrote:
> The fact that Swift uses the exact same syntax ("a") for String, Character, and UnicodeScalar can get annoying at times. When unconstrained it's always String, and the only way to disambiguate between the two when used in a context that takes both Character and UnicodeScalar is to explicitly constraint it further, e.g. with `"a" as Character`. A trivial example of this in action is
> var s = ""
> s.append("c")
> This code looks pretty straightforward, but it throws an ambiguity error (and the annoying part is, it doesn't actually matter which way it's resolved, the behavior is the same).
> Having to type `"c" as Character` and `"c" as UnicodeScalar` can get pretty annoying if you have to do it a lot. It would be great to reduce this typing a bit.

In principle you should also be able to say “s.append(Character(“c”))” but I agree that isn’t much better.

> My initial proposal here is to introduce string literal suffixes. Let me type something like `"c"c` for a Character and `"c"us` for a UnicodeScalar (and maybe `"c"s` to explicitly mean a String, although that's the default if unconstrained). AFAIK this is not ambiguous with the current syntax, as I don't believe it's ever legal to put an identifier like that after a string.

I’m not sure how I feel about this proposal :-).  

On the one hand, I totally agree that this can be an issue.
On the other hand: I haven’t heard this be a wide-spread complaint.  It smacks of the “123ull” sorts of suffixes in C, which are pretty grotty IMO.  It reduces clarity of code by introducing syntax magic.

If you’re interested in pursuing this, I’d ask you to think about a few different things:

1) How does this generalize to integer, FP and other literals we have?
2) How do we avoid baking these into the compiler?  We would want to allow the suffixes to be user extensible, and have the standard ones defined by the standard library.  For example, “a”c could be sugar for c(“a”) or something.
3) There are C extensions that support things like _128 as well, should we support numbers?  Keep in mind that integer literals in swift support 123_456_789 separators.
4) Exactly which ones would we add to Swift out of the box?  Do we go down the C path of only having them for large ones (but ignores “short”)?  


More information about the swift-evolution mailing list