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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...