[swift-evolution] Strings in Swift 4

Brent Royal-Gordon brent at architechies.com
Fri Feb 10 21:23:32 CST 2017


> On Feb 10, 2017, at 5:49 PM, Jonathan Hull via swift-evolution <swift-evolution at swift.org> wrote:
> 
> An easier to implement, but slightly less useful approach, would be to have methods which take an array of indexes along with the proposed change, and then it adjusts the indexes (or replaces them with nil if they are invalid) as it makes the update.  For example:
> 
> 	func append(_ element:Element, adjusting: [Index]) -> [Index?]
> 	func appending(_ element:Element, adjusting: [Index]) -> (Self, [Index?])

This is a very interesting idea. A couple observations:

1. The problem of adjusting indices is not just a String one. It also applies to Array, among other things.

2. This logic could be encapsulated and reused in a separate type. For instance, imagine:

	let myStringProxy = IndexTracking(collection: myString, trackedIndices: [someIndex, otherIndex])
	myStringProxy.insert("foo", at: otherIndex)
	(someIndex, otherIndex) = (stringProxy.trackedIndices[0], stringProxy.trackedIndices[1])

Or, with a helper method:

	myString.withTracked(&someIndex) { myStringProxy in
		myStringProxy.insert("foo", at: otherIndex)
	}

3. An obstacle to doing this correctly is that a collection's index invalidation behavior is not expressed in the type system. If there were a protocol like:

	protocol RangeReplaceableWithEarlierIndexesStableCollection: RangeReplaceableCollection {}

That would help us here.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list