
具体来说,我正在尝试以下几点:
let str = "Hello,playground"let prefixrange = str.startIndex..<str.startIndex.advancedBy(5) // error
第二行给我以下错误
‘advancedBy’ is unavailable: To advance an index by n steps call ‘index(_:offsetBy:)’ on the CharacterVIEw instance that produced the index.
我看到String有以下方法。
str.index(after: String.Index)str.index(before: String.Index)str.index(String.Index,offsetBy: String.Indexdistance)str.index(String.Index,offsetBy: String.Indexdistance,limitedBy: String.Index)
这些真的让我很困惑,所以我开始玩弄他们,直到我理解他们为止。我在下面添加一个答案来展示如何使用它们。
以下所有示例都使用
var str = "Hello,playground"
startIndex和endindex
> startIndex是第一个字符的索引
> endindex是最后一个字符之后的索引。
例
// characterstr[str.startIndex] // Hstr[str.endindex] // error: after last character// rangelet range = str.startIndex..<str.endindexstr[range] // "Hello,playground"
后
如下:index(after:String.Index)
>之后直接指向给定索引后的字符索引。
例子
// characterlet index = str.index(after: str.startIndex)str[index] // "e"// rangelet range = str.index(after: str.startIndex)..<str.endindexstr[range] // "ello,playground"
之前
如下:index(before:String.Index)
> before指的是直接在给定索引之前的字符的索引。
例子
// characterlet index = str.index(before: str.endindex)str[index] // d// rangelet range = str.startIndex..<str.index(before: str.endindex)str[range] // Hello,playgroun
offsetBy
如下:index(String.Index,offsetBy:String.Indexdistance)
> offsetBy值可以为正或负,并从给定索引开始。虽然它是String.Indexdistance类型,可以给它一个Int。
例子
// characterlet index = str.index(str.startIndex,offsetBy: 7)str[index] // p// rangelet start = str.index(str.startIndex,offsetBy: 7)let end = str.index(str.endindex,offsetBy: -6)let range = start..<endstr[range] // play
limitedBy
如下:index(String.Index,offsetBy:String.Indexdistance,restrictedBy:String.Index)
> limitedBy对于确保偏移量不会导致索引超出范围是有用的。这是一个有界的指数。由于偏移量可能超过限制,此方法返回可选。如果索引超出范围,则返回nil。
例
// characterif let index = str.index(str.startIndex,offsetBy: 7,limitedBy: str.endindex) { str[index] // p} 如果偏移量是77而不是7,那么if语句将被跳过。
总结以上是内存溢出为你收集整理的String.Index在Swift 3中如何工作全部内容,希望文章能够帮你解决String.Index在Swift 3中如何工作所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)