本文介绍了Swift 3.0遍历String.Index范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是使用Swift 2.2的可能:

The following was possible with Swift 2.2:

let m = "alpha"
for i in m.startIndex..<m.endIndex {
    print(m[i])
}
a
l
p
h
a

使用3.0时,出现以下错误:

With 3.0, we get the following error:

我正在尝试快速处理字符串-只是遍历字符串的前半部分(或更常见的问题:遍历字符串的范围).

I am trying to do a very simple operation with strings in swift -- simply traverse through the first half of the string (or a more generic problem: traverse through a range of a string).

我可以执行以下操作:

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

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

But here I'm not really traversing the string. So the question is: how do I traverse through a range of a given string. Like:

for i in Range(s.startIndex..<s.midIndex) {
    print(s[i])
}

推荐答案

您可以使用characters属性的indices属性来遍历字符串,如下所示:

You can traverse a string by using indices property of the characters property like this:

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, t, r, i, n, g
}

文档字符串和字符-计数字符:

强调是我自己的.

这不起作用:

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

这篇关于Swift 3.0遍历String.Index范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:51