We really don't want to make subscripting a non-O(1) operation. That just 
provides false convenience and encourages people to do the wrong thing with 
Strings anyway.

I'm always interested in why people want this kind of ability. Yes, it's nice 
for teaching programming to be able to split strings on character boundaries 
indexed by integers, but where does it come up in real life? The most common 
cases I see are trying to strip off the first or last character, or a known 
prefix or suffix, and I feel like we should have better answers for those than 
"use integer indexes" anyway.

Jordan


> On Dec 13, 2017, at 22:30, Cao, Jiannan via swift-dev <swift-dev@swift.org> 
> wrote:
> 
> Hi,
> 
> I would like to discuss the String.Index problem within Swift. I know the 
> current situation of String.Index is based on the nature of the underlaying 
> data structure of the string.
> 
> But could we just make String.Index contain offset information? Or make 
> offset index subscript available for accessing character in String?
> 
> for example:
> let a = "01234"
> print(a[0]) // 0
> print(a[0...4]) // 01234
> print(a[...]) // 01234
> print(a[..<2]) // 01
> print(a[...2]) // 012
> print(a[2...]) // 234
> print(a[2...3]) // 23
> print(a[2...2]) // 2
> if let number = a.index(of: "1") {
>     print(number) // 1
>     print(a[number...]) // 1234
> }
> 
> 
> 0 equals to Collection.Index of collection.index(startIndex, offsetBy: 0)
> 1 equals to Collection.Index of collection.index(startIndex, offsetBy: 1)
> ...
> we keep the String.Index, but allow another kind of index, which is called 
> "offsetIndex" to access the String.Index and the character in the string.
> Any Collection could use the offset index to access their element, regarding 
> the real index of it.
> 
> I have make the Collection OffsetIndexable protocol available here, and make 
> it more accessible for StringProtocol considering all API related to the 
> index.
> 
> https://github.com/frogcjn/OffsetIndexableCollection-String-Int-Indexable- 
> <https://github.com/frogcjn/OffsetIndexableCollection-String-Int-Indexable->
> 
> If someone want to make the offset index/range available for any collection, 
> you just need to extend the collection:
> extension String : OffsetIndexableCollection {
> }
> 
> extension Substring : OffsetIndexableCollection {
> }
> 
> 
> I hope the Swift core team could consider bring the offset index to string, 
> or make it available to other collection, thus let developer to decide 
> whether their collection could use offset indices as an assistant for the 
> real index of the collection.
> 
> 
> Thanks!
> Jiannan
> 
> 
> _______________________________________________
> swift-dev mailing list
> swift-dev@swift.org
> https://lists.swift.org/mailman/listinfo/swift-dev

_______________________________________________
swift-dev mailing list
swift-dev@swift.org
https://lists.swift.org/mailman/listinfo/swift-dev

Reply via email to