[Pitch] String prefix operator

Motivational example:

var urlString = self.urlString
if urlString.hasPrefix("//") {
  urlString = "http:" + urlString // urlString needs to be typed twice
}

While there is currently an easy way to append string using +=, there is no shortcut for prefixing a string. What I propose is adding a =+ operator for prefixing the string:

urlString =+ "http:"

Would anyone else find it useful?

urlString =+ "http:"

Would anyone else find it useful?

Well, I mean, maybe sometimes, in terms of expressiveness. But there are a few problems:

* It's kind of misleading, because this is very likely to be *far* less efficient than `+=`. Rather than appending to the existing string buffer, it will probably have to completely rebuild it.
* The whole expression is backwards. It probably *ought* to be something more like `"http:" =+ urlString`, but that looks funny because assignment always flows to the left. Perhaps it would be better to define a left-to-right assignment operator, like `->`, and then use `->+` for this, except that'd be kind of ridiculous.

In theory, this construct would be equally useful for other non-commutative operators, like `-` and `/` in arithmetic. In practice, I've never seen any language do this. It just doesn't seem to be an operation people need that often, from what I can tell.

var urlString = self.urlString
if urlString.hasPrefix("//") {
  urlString = "http:" + urlString // urlString needs to be typed twice
}

Well, you *can* do this:

  urlString.replaceSubrange(urlString.startIndex ..< urlString.startIndex, with: "http:")

Okay, so maybe that's not better by itself. But with a couple extension methods, we can do better:

  extension String {
    mutating func insert(_ string: String, at index: Index) {
      replaceSubrange(index..<index, with: string)
    }
    
    mutating func prepend(_ string: String) {
      insert(string, at: startIndex)
    }
  }

Now we have:

  urlString.prepend("http:")

Much better—and without the issues of `=+`.

···

--
Brent Royal-Gordon
Architechies