加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 3.0迭代String.Index范围

发布时间:2020-12-14 05:44:33 所属栏目:百科 来源:网络整理
导读:使用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])
}
a
l
p
h
a

使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读