是时候承认失败…
在Objective-C中,我可以使用类似:
NSString* str = @"abcdefghi"; [str rangeOfString:@"c"].location; // 2
在Swift中,我看到类似的东西:
var str = "abcdefghi" str.rangeOfString("c").startIndex
…但是只是给我一个String.Index,我可以使用下标回原始字符串,但不提取位置。
FWIW,String.Index有一个私有的ivar称为_position,它具有正确的值。我只是不看看它是如何暴露。
我知道我可以很容易地添加到字符串自己。我更好奇我在这个新的API中失踪。
你不是唯一一个找不到解决方案的人。
原文链接:https://www.f2er.com/swift/321775.htmlString不实现RandomAccessIndexType。可能是因为它们支持具有不同字节长度的字符。这就是为什么我们必须使用string.characters.count(在Swift 1.x中的count或countElements)来获取字符数。这也适用于职位。 _position可能是一个索引到原始数组的字节,他们不想暴露。 String.Index旨在保护我们在字符中间访问字节。
这意味着您获得的任何索引必须从String.startIndex或String.endIndex(String.Index实现BidirectionalIndexType)创建。任何其他索引可以使用后继或前导方法创建。
现在为了帮助我们索引,有一组方法(Swift 1.x中的函数):
Swift 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)
Swift 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
Swift 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是麻烦的,但使用包装器以整数索引(见http://stackoverflow.com/a/25152652/669586)是危险的,因为它隐藏了真实索引的低效率。
请注意,Swift索引实现存在的问题是,为一个字符串创建的索引/范围不能可靠地用于不同的字符串,例如:
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]
Swift 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]