Swift 3.0迭代String.Index范围

前端之家收集整理的这篇文章主要介绍了Swift 3.0迭代String.Index范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用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

猜你在找的Swift相关文章