对于大多数Swift Collections,Collection's SubSequence的索引与基本Collection兼容。
func foo<T: Collection>(_ buffer: T) -> T.Iterator.Element
where T.Index == T.SubSequence.Index
{
let start = buffer.index(buffer.startIndex, offsetBy: 2)
let end = buffer.index(buffer.startIndex, offsetBy: 3)
let sub = buffer[start ... end]
return buffer[sub.startIndex]
}这对于大多数收藏品来说都很好:
print(foo([0, 1, 2, 3, 4])) // 2甚至对String.UTF8View来说
print(foo("01234".utf8) - 0x30 /* ASCII 0 */) // 2但是当使用String.CharacterView的时候,事情就开始崩溃了:
print(foo("01234".characters)) // "0"对于CharacterView,SubSequences创建完全独立的实例,即索引再次从0开始。要将其转换回主字符串索引,必须使用distance函数并将其添加到主String中的SubSequence的startIndex中。
func foo<T: Collection>(_ buffer: T) -> T.Iterator.Element
where T.Index == T.SubSequence.Index, T.SubSequence: Collection, T.SubSequence.IndexDistance == T.IndexDistance
{
let start = buffer.index(buffer.startIndex, offsetBy: 2)
let end = buffer.index(buffer.startIndex, offsetBy: 3)
let sub = buffer[start ... end]
let subIndex = sub.startIndex
let distance = sub.distance(from: sub.startIndex, to: subIndex)
let bufferIndex = buffer.index(start, offsetBy: distance)
return buffer[bufferIndex]
}这样,所有三个示例现在都正确地打印了2。
distance(from:to:)来转换索引?发布于 2016-10-23 13:02:06
这是论快速进化,作为bug报告SR-1927 -字符串视图的子序列行为不正确文件,最近在StringCharacterView.swift和提交中进行了修复。
有了这个修复,String.CharacterView的行为就像其他集合一样,因为它的切片应该对相同的元素使用与原始集合相同的索引。
https://stackoverflow.com/questions/40202639
复制相似问题