[swift-evolution] [Pitch] String prefix operator

Erica Sadun erica at ericasadun.com
Sun Jun 19 11:37:18 CDT 2016


> On Jun 18, 2016, at 4:44 PM, Xiaodi Wu via swift-evolution <swift-evolution at swift.org> wrote:
> 
> On Sat, Jun 18, 2016 at 4:50 PM, Michael Peternell via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
> 
> > Am 17.06.2016 um 07:45 schrieb Charlie Monroe via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>>:
> >
> > 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?
> 
> No. What I would find useful though, is to recognize that addition is not string concatenation. There is a strong convention in mathematics that the "+" symbol should only be used for operations that are commutative. String concatenation is not commutative. (There are more conventions regarding "+", but all of them are respected by numbers, vectors, complex numbers, quaternions, or matrices - just to name a few.)
> 
> I would like to have a different operator for string concatenation.
> 
> I don't see how this would measurably improve Swift code. IIUC, much of the problem with `+` and strings arises from implicit conversions that don't happen in Swift. It's not even possible to write a generic algorithm that accidentally confuses arithmetic `+` and string concatenation `+`, since you would have to retroactively conform strings and numeric types to a nonsensical protocol of your own making.

I concur. 

I am willing to live with the redundancy in the urlString example for the following reasons:
Like (other) streams, Swift strings prioritize "append" operations. This is how `+` now works.
If we tie ourselves to mathematical convention, Swift becomes a different language. Consider the Swift assignment operator (`=`), which is definitely not commutative. IMO, Swift uses mathematical conventions. Mathematical conventions do not define Swift. 
Prefixing does not place such an undue burden on the user that I think it warrants language modification
-- E


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160619/11ad22d0/attachment.html>


More information about the swift-evolution mailing list