gpt4 book ai didi

Swift 3.0 遍历 String.Index 范围

转载 作者:IT王子 更新时间:2023-10-29 05:08:11 28 4
gpt4 key购买 nike

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

来自documentationStrings and Characters - Counting Characters 部分:

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 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38386969/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com