Swift 3.0 迭代 String.Index 范围 [英] Swift 3.0 iterate over String.Index range

查看:19
本文介绍了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:

类型'Range'(又名'Range')不符合协议'Sequence'

Type 'Range' (aka 'Range') does not conform to protocol 'Sequence'

我正在尝试用 swift 对字符串进行一个非常简单的操作——只需遍历字符串的前半部分(或者更通用的问题:遍历字符串的范围).

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
}

来自文档部分字符串和字符 - 计算字符:

扩展的字素簇可以由一个或多个 Unicode 标量组成.这意味着不同的字符——以及同一字符的不同表示——可能需要不同数量的内存来存储.因此,Swift 中的每个字符在字符串表示中占用的内存量并不相同.因此,如果不遍历字符串,就无法计算字符串中的字符数以确定其扩展的字素簇边界.

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 范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆