Swift allows custom postfix, prefix, and infix operators, but I find myself also wishing for custom string delimiters to indicate different categories of strings - localizable, user interface identifiers, resource names, etc. Unicode has lots of options for expressive delimiters, some of which aren't too hard to type on a standard Mac US keyboard, such as «», ‹›, and “” (curly quotes).
A currently available option is to create a custom prefix/postfix operator and apply it to a regular string literal, such as §"image_name", but I think using other delimiters could make it more distinctive and expressive.
An idea for how this might work:
delimiter operator «»
delimiter func «»(stringLiteral: String) -> NSUserInterfaceItemIdentifier
{
return NSUserInterfaceItemIdentifier(rawValue: stringLiteral)
}
delimiter func «»(stringLiteral: String) -> NSimage.Name
{
return NSImage.Name(rawValue: stringLiteral)
}
This adds delimiter
to the existing operator types, where the delimiter is a pair of characters. Should multi-character delimiters be allowed? My gut feeling is that would be too complicated, so I'm recommending a simple pair.
Once the delimiter is defined, you can define functions that take a string literal and return some non-Void type. As with generic functions that differ only in their return type, the compiler could determine which overload of the function to use depending on the context.
A string literal with a custom delimiter would of course have to allow for escaping the closing delimiter in case you wanted to have it as part of the string, and that seems straightforward enough, like «example\»string»
.
I considered a requirement that the function return a type that conforms to ExpressibleByStringLiteral and/or RawRepresentable, since those are related concepts, but couldn't think of exactly what value such a restriction would actually add.
Thoughts? Has this been discussed before? I searched and couldn't find anything.