[swift-evolution] Pitch: Limit typealias extensions to the typealias

Yvo van Beek yvo at yvo.net
Thu Jun 8 23:14:17 CDT 2017

Typealiases can greatly reduce the complexity of code. But I think one
change in how the compiler handles them could make them even more powerful.

Let's say I'm creating a web server framework and I've created a simple
dictionary to store HTTP headers (I know that headers are more complex than
that, but as an example). I could write something like this:

    typealias HeaderKey = String

  var headers = [HeaderKey: String]()
  headers["Host"] = "domain.com"

Now I can define a couple of default headers like this:

  extension HeaderKey {
    static var lastModified: String { return "Last-Modified" }
    static var host: String { return "Host" }

After that I can do this:

  var headers = [HeaderKey: String]()
  headers[.host] = "domain.com"
  headers[.lastModified] = "some date"
  headers["X-MyHeader"] = "This still works too"

But unfortunately the extension is also applied to normal strings:

    var normalString: String = .host

Perhaps it would be better if the extension would only apply to the parts
of my code where I use the HeaderKey typealias and not to all Strings. This
could be a great tool to specialize classes by creating a typealias and
adding functionality to it. Another example I can think of is typealiases
for dictionaries or arrays with added business logic through extensions
(especially since you can't inherit from structs).

If you want to create an extension that adds functionality to all Strings
you could have created an extension for String instead of HeaderKey.

Please let me know what you think. I'm not sure how complex this change
would be.
I could write a proposal if you're interested.

Kind regards,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170609/22ba2997/attachment.html>

More information about the swift-evolution mailing list