Custom literals

I had an (crazy) idea as custom user literals could look like

typealias + generic

typealias<T> [T] = Array<T>
typealias<T> T? = Optional<T>
typealias<K: Hashable, T> [K: T] = Dictionary<K, T>

or without generic

typealias [T] = Array<T>
typealias T? = Optional<T>
typealias [K: T] = Dictionary<K, T>

I mean that actually type literals can be a private case of typeliases, may make sense to summarize this abstraction and give programmers the opportunity to create their own literals

I understand that the implementation can be difficult and likely to slow down the compiler, but it seemed interesting to discuss it

I believe what you're describing here is Swift's syntactic sugar over certain common type declarations, right? It sounds to me like you're interested in extending that mechanism and allowing the declaration of additional type shorthands at compile-time. What set of characters would you suggest be made available for use with custom shorthands? Can you give some examples of how you'd use this feature if it were added to the language?

If we took this proposal to the extreme and said that any sequence of characters could be repurposed for a new shorthand, then I suspect it would make parsing Swift as undecidable as it is in Perl 5. So that'd be fun!

1 Like

It is difficult for me to say which characters set could be used as I am not very immersed in how the parser works for Swift, presumably it should be the same characters as for operators except "<", ">"

example:
typealias<A, B> A | B = Union<A, B>

I like the idea, but it’s probably difficult to implement in practice. Btw, the particular case above is simpler than the general case, since it could be seen as an infix operator, albeit for types. Perhaps that kind of thing could be implemented.

1 Like
Terms of Service

Privacy Policy

Cookie Policy