Swift 3.0迭代String.Index范围

Swift 3.0迭代String.Index范围,第1张

概述使用Swift 2.2可以实现以下功能: let m = "alpha"for i in m.startIndex..<m.endIndex { print(m[i])}alpha 使用3.0,我们收到以下错误: Type ‘Range’ (aka ‘Range’) does not conform to protocol ‘Sequence’ 我试图用swift中的字符串做 使用Swift 2.2可以实现以下功能:
let m = "Alpha"for i in m.startIndex..<m.endindex {    print(m[i])}alpha

使用3.0,我们收到以下错误:

Type ‘Range’ (aka ‘Range’) does not conform to protocol ‘Sequence’

我试图用swift中的字符串做一个非常简单的 *** 作 – 简单地遍历字符串的前半部分(或者更通用的问题:遍历字符串的范围).

我可以做以下事情:

let s = "string"var midindex = s.index(s.startIndex,offsetBy: s.characters.count/2)let r = Range(s.startIndex..<midindex)print(s[r])

但在这里,我并没有真正遍历这个字符串.所以问题是:如何遍历给定字符串的范围.喜欢:

for i in Range(s.startIndex..<s.midindex) {    print(s[i])}
您可以使用characters属性的indices属性遍历字符串,如下所示:
let letters = "string"let mIDdle = letters.index(letters.startIndex,offsetBy: letters.characters.count / 2)for index in letters.characters.indices {    // to traverse to half the length of string     if index == mIDdle { break }  // s,t,r    print(letters[index])  // s,r,i,n,g}

从字符串和字符中的documentation开始 – 计数字符:

Extended grapheme clusters can be composed of one or more Unicode scalars. This means that different characters—and different representations of the same character—can require different amounts of memory to store. Because of this,characters in Swift do not each take up the same amount of memory within a string’s representation. As a result,the number of characters in a string cannot be calculated without iterating through the string to determine its extended grapheme cluster boundarIEs.

重点是我自己的.

这不起作用:

let secondChar = letters[1] // error: subscript is unavailable,cannot subscript String with an Int
总结

以上是内存溢出为你收集整理的Swift 3.0迭代String.Index范围全部内容,希望文章能够帮你解决Swift 3.0迭代String.Index范围所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1048317.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存