您不是唯一找不到解决方案的人。
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 timeslet 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 abovelet 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 timeslet 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 abovelet 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 timeslet lastChar: Character = text[index2] //now we can index!let lastChar2 = text.characters[index2] //will do the same as abovelet 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 timeslet 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它很麻烦,但是使用包装器按整数索引很危险,因为它掩盖了实际索引的效率低下。
请注意,Swift索引实现存在一个问题,即为 一个字符串创建的索引/范围不能可靠地用于其他字符串 ,例如:
斯威夫特2.x
let text: String = "abc"let text2: String = "欢迎分享,转载请注明来源:内存溢出
评论列表(0条)