[swift-evolution] [Pitch] String prefix operator

Brent Royal-Gordon brent at architechies.com
Fri Jun 17 06:45:05 CDT 2016


> 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



More information about the swift-evolution mailing list