[swift-evolution] Pitch: String Index Overhaul

Dave Abrahams dabrahams at apple.com
Sat Jun 3 19:10:00 CDT 2017

on Sat Jun 03 2017, Ben Rimmington <me-AT-benrimmington.com> wrote:

>> On 27 May 2017, at 18:40, Dave Abrahams wrote:
>> ## Introduction
>> Today `String` shares an `Index` type with its `CharacterView` but not
>> with its `UTF8View`, `UTF16View`, or `UnicodeScalarView`.  This
>> proposal redefines `String.UTF8View.Index`, `String.UTF16View.Index`,
>> and `String.CharacterView.Index` as typealiases for `String.Index`,
>> and exposes a public `encodedOffset` property and initializer that can
>> be used to serialize and deserialize positions in a `String` or
>> `Substring`.
> If `encodedOffset` is only needed for serialization of indices, 

It's not only needed for that.  Once StringProtocol provides access to
its underlying code units, the encodedOffset will be useful information
in other ways.

> could `String.Index` conform to `Codable` from SE-0166 instead?

Not instead, definitely.  Additionally, maybe; that's a separate

>> ## Proposed solution
>> All `String` views will use a single index type (`String.Index`), so
>> that positions can be interchanged without awkward explicit
>> conversions:
>> ```swift
>> let html: String = "See <a href=\"http://swift.org\">swift.org</a>"
>> // Search the UTF16, instead of characters, for performance reasons:
>> let open = "<".utf16.first!, close = ">".utf16.first!
>> let tagStart = s.utf16.index(of: open)
>> let tagEnd = s.utf16[tagStart...].index(of: close)
> I think `s` should be `html` in the previous two lines.

Ah, yeah, thanks; good catch!


More information about the swift-evolution mailing list