This particular effort was not started to create a perfect API. It is to respond to a community-sourced need that is not satisfied by the current standard library. That's why I've been wavering between producing a Substring and String. This is really the first effort to push into this community-driven space. As I review the original use-cases, they are meant to produce Strings without coercion, and where efficiency is not a motivating factor.
If we are driven by a particular use-case, how far should we go with that muse. Certainly we want something to be as useful as possible and as Swifty as possible but if we start returning Substrings, I can foresee many libraries implementing var trimmedAsString because we're not giving people the tool that does what they want and need. Producing a string isn't the most efficient approach nor is it the most general but it provides tooling that expresses the task common to an overwhelming number of use cases.
In exploring this area, pulling on a single thread is proving to unravel a much bigger problem than we set out to solve.
To recap:
- Andrew discovered a great demand for
String.trim. - We did not want this tooling to depend on Cocoa.
- We wanted to add a simple way to offer start-or-end trimming.
- We wanted to define what whitespace meant.
- We wanted to define what a general trimming API would look like.
Maybe the What Characters are and are not whitespace? discussion should be expanded to include all pertinent character sets. Perhaps some of that work has already been covered in Character properties. And maybe that's a can that can be kicked down the road as an implementation detail that can be changed without Swift Evolution discussion.
trimmingCharacters(in:) is a part of StringProtocol. We may want to enhance that API to include from: for .start and .end. If StringProtocol offers trimmingCharacters(in:, from: = default), this proposal becomes way simpler because it just has to call it with whatever the character set for newlines and whitespaces becomes. At the same time, trimmingCharacters(in:) returns String. Maybe it shouldn't. Also, strings aren't the only trimmable thing: so are arrays or really any bidirectionalcollection.
Anyway, I don't want to lose sight of our brief: introduce a convenient way to trim a string.