您不是唯一找不到解决方案的人。
String
没有实现RandomAccessIndexType
。可能是因为它们启用了具有不同字节长度的字符。这就是为什么我们必须使用string.characters.count
(count
或countElements
在Swift 1.x中)获取字符数的原因。这也适用于职位。的_position
可能是一个索引字节的原始阵列,他们不希望公开这一点。本String.Index
是为了保护我们从人物的中间访问字节。
这意味着您必须从String.startIndex
或String.endIndex
(String.Index
实现BidirectionalIndexType
)创建任何索引。可以使用successor
或predecessor
方法创建任何其他索引。
现在可以使用索引来帮助我们,它提供了一组方法(Swift 1.x中的函数):
斯威夫特4.x
let text = "abc"
let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let characterIndex2 = text.index(text.startIndex, offsetBy: 2)
let lastChar2 = text[characterIndex2] //will do the same as above
let range: Range<String.Index> = text.range(of: "b")!
let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)
斯威夫特3.0
let text = "abc"
let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let characterIndex2 = text.characters.index(text.characters.startIndex, offsetBy: 2)
let lastChar2 = text.characters[characterIndex2] //will do the same as above
let range: Range<String.Index> = text.range(of: "b")!
let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)
斯威夫特2.x
let text = "abc"
let index2 = text.startIndex.advancedBy(2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let lastChar2 = text.characters[index2] //will do the same as above
let range: Range<String.Index> = text.rangeOfString("b")!
let index: Int = text.startIndex.distanceTo(range.startIndex) //will call successor/predecessor several times until the indices match
斯威夫特1.x
let text = "abc"
let index2 = advance(text.startIndex, 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let range = text.rangeOfString("b")
let index: Int = distance(text.startIndex, range.startIndex) //will call succ/pred several times
使用String.Index
它很麻烦,但是使用包装器按整数索引(请参阅https://stackoverflow.com/a/25152652/669586)很危险,因为它掩盖了实际索引的效率低下。
请注意,Swift索引实现存在一个问题,即为一个字符串创建的索引/范围不能可靠地用于其他字符串,例如:
斯威夫特2.x
let text: String = "abc"
let text2: String = "🎾🏇🏈"
let range = text.rangeOfString("b")!
//can randomly return a bad substring or throw an exception
let substring: String = text2[range]
//the correct solution
let intIndex: Int = text.startIndex.distanceTo(range.startIndex)
let startIndex2 = text2.startIndex.advancedBy(intIndex)
let range2 = startIndex2...startIndex2
let substring: String = text2[range2]
斯威夫特1.x
let text: String = "abc"
let text2: String = "🎾🏇🏈"
let range = text.rangeOfString("b")
//can randomly return nil or a bad substring
let substring: String = text2[range]
//the correct solution
let intIndex: Int = distance(text.startIndex, range.startIndex)
let startIndex2 = advance(text2.startIndex, intIndex)
let range2 = startIndex2...startIndex2
let substring: String = text2[range2]